Thread ללוגיקה ול-render, עם סנכרוןA thread for logic and rendering, with sync
מפרידים את הלוגיקה מהציור ל-threads נפרדים, משתפים מצב בבטחה, ומשווים ל-Swing Timer.
Separating logic from drawing into their own threads, sharing state safely, and comparing with a Swing Timer.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- תמונת מצב: עותק בלתי משתנה של העולם (record עם
List.copyOf). ה-thread של הלוגיקה בונה חדש בכל טיק ומפרסם דרך volatile; ה-render תמיד רואה עולם שלם, אף פעם לא חצי.snapshot: An immutable copy of the world (a record withList.copyOf). The logic thread builds a new one each tick and publishes it through volatile; the renderer always sees a whole world, never half of one. - צעד זמן קבוע: צוברים את זמן הפריימים, ומריצים עדכון של, נניח, 20ms בכל פעם שהצטבר מספיק. הפיזיקה יציבה וזהה בכל מחשב.fixed timestep: Accumulate frame time, and run an update of, say, 20ms each time enough has built up. Physics stays stable and identical on every computer.
- double buffering: שני חוצצים: מציירים על האחורי, ואז מחליפים. המסך לא מראה אף פעם פריים חצי מצויר.double buffering: Two buffers: draw on the back one, then swap. The screen never shows a half-drawn frame.
- Event Dispatch Thread: ה-thread היחיד שמותר לו לגעת ברכיבי Swing.
javax.swing.Timerרץ עליו, ולכן משחק פשוט עם Timer לא צריך סנכרון בכלל.Event Dispatch Thread: The only thread allowed to touch Swing components.javax.swing.Timerruns on it, so a simple game with a Timer needs no synchronization at all.
02לוגיקה ו-render, עם תמונת מצבLogic and render, with a snapshot
ה-thread של הלוגיקה בונה רשימת אויבים חדשה בכל טיק, ומפרסם תמונת מצב בלתי משתנה במשתנה volatile. ה-render קורא את ההפניה פעם אחת ומצייר ממנה, ולכן אף פעם לא רואה עולם חצי מעודכן.
The logic thread builds a new enemy list each tick, and publishes an immutable snapshot in a volatile variable. The renderer reads the reference once and draws from it, so it never sees a half-updated world.
import java.util.ArrayList;
import java.util.List;
public class Main {
record Enemy(int x, int y) {
}
record Snapshot(int tick, List<Enemy> enemies) {
}
static volatile Snapshot latest = new Snapshot(0, List.of());
public static void main(String[] args) throws InterruptedException {
Thread logic = new Thread(() -> {
List<Enemy> world = new ArrayList<>(List.of(new Enemy(0, 0), new Enemy(10, 5)));
for (int tick = 1; tick <= 100; tick++) {
List<Enemy> next = new ArrayList<>();
for (Enemy e : world) {
next.add(new Enemy(e.x() + 1, e.y()));
}
world = next;
latest = new Snapshot(tick, List.copyOf(world));
}
});
Thread render = new Thread(() -> {
int drawn = 0;
while (latest.tick() < 100) {
Snapshot s = latest;
if (s.enemies().size() != 2 && s.tick() > 0) {
System.out.println("torn frame!");
}
drawn++;
}
System.out.println("render saw a whole world every time");
});
logic.start();
render.start();
logic.join();
render.join();
System.out.println("final " + latest);
}
}render saw a whole world every time final Snapshot[tick=100, enemies=[Enemy[x=100, y=0], Enemy[x=110, y=5]]]
5 הרצות אמיתיות בזמן בניית האתר (JDK 21):5 real runs while building the site (JDK 21):
| הפלטOutput | כמה פעמיםTimes |
|---|---|
render saw a whole world every time
final Snapshot[tick=100, enemies=[Enemy[x=100, y=0], Enemy[x=110, y=5]]] | 5 |
volatile: האם העובד רואה את השינוי?volatile: does the worker see the change?
03טיימר במקום threadA timer instead of a thread
scheduleAtFixedRate מריץ טיק כל 10ms על thread אחד. ב-Swing, javax.swing.Timer עושה אותו דבר על ה-EDT, ואז אין שני threads ואין מה לסנכרן.
scheduleAtFixedRate runs a tick every 10ms on one thread. In Swing, javax.swing.Timer does the same on the EDT, so there aren't two threads and nothing to synchronize.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) throws InterruptedException {
ScheduledExecutorService loop = Executors.newSingleThreadScheduledExecutor();
List<Integer> ticks = new ArrayList<>();
loop.scheduleAtFixedRate(() -> ticks.add(ticks.size() + 1), 0, 10, TimeUnit.MILLISECONDS);
Thread.sleep(105);
loop.shutdown();
loop.awaitTermination(1, TimeUnit.SECONDS);
System.out.println("about 10 ticks: " + (ticks.size() >= 8 && ticks.size() <= 12));
}
}about 10 ticks: true
3 הרצות אמיתיות בזמן בניית האתר (JDK 21):3 real runs while building the site (JDK 21):
| הפלטOutput | כמה פעמיםTimes |
|---|---|
about 10 ticks: true | 3 |
מה קורה בתוך thread poolWhat happens inside a thread pool
04טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says
אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.
These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.
צייד באגים: אויב נולד באמצע לולאה
Bug hunter: an enemy born mid-loop
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> enemies = new ArrayList<>(List.of("bat", "orc"));
for (String e : enemies) {
if (e.equals("orc")) {
enemies.add("orc-baby");
}
}
System.out.println(enemies);
}
}Exception in thread "main" java.util.ConcurrentModificationException at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1095) at java.base/java.util.ArrayList$Itr.next(ArrayList.java:1049) at Main.main(Main.java:7)
java.util.ConcurrentModificationException: מוסיפים לרשימה בזמן שה-for-each עובר עליה. ב-thread אחר זה היה קורה גם בלי להוסיף בתוך הלולאה.java.util.ConcurrentModificationException: adding to the list while the for-each walks it. On another thread it would happen even without adding inside the loop.צפו איפה זה נשברWatch where it breaks
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
05הצעד של היום בפרויקט מדףToday's step in the Shelf project
1000 אויבים. בכל טיק מחלקים ל-4 חלקים, כל חלק מתעדכן במשימה משלו (בריכה של 4), ומחברים לעולם חדש. כל Enemy.step() מחזיר אויב חדש (בלי לשנות את הקיים), אז אין מה לנעול. אחרי 10 טיקים: 1000 enemies, 333 reached x>=30, enemy 5 at x=30.
1000 enemies. Each tick split into 4 parts, each part updated in its own task (a pool of 4), and joined into a new world. Every Enemy.step() returns a new enemy (without changing the old one), so there's nothing to lock. After 10 ticks: 1000 enemies, 333 reached x>=30, enemy 5 at x=30.
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.
סיימתם את ההרצאה!Lecture complete!
עכשיו המצגת לחזרה מהירה, או ישר לתרגול.
Next: the slides for a quick review, or straight to practice.