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.
פרסום תמונת מצבPublishing a snapshot
תזכורת: מה ביקשוReminder: the task
record Snapshot(int tick, List<String> enemies) ומשתנה static volatile Snapshot latest. thread לוגיקה מפרסם שלוש תמונות. אחרי join הדפיסו tick 3 [bat@3, orc@6].
record Snapshot(int tick, List<String> enemies) and a static volatile Snapshot latest. A logic thread publishes three snapshots. After join print tick 3 [bat@3, orc@6].
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
volatile: האם העובד רואה את השינוי?volatile: does the worker see the change?
הפתרון המלא והפלט שלוFull solution and its output
import java.util.List;
public class Main {
record Snapshot(int tick, List<String> enemies) {
}
static volatile Snapshot latest = new Snapshot(0, List.of());
public static void main(String[] args) throws InterruptedException {
Thread logic = new Thread(() -> {
for (int t = 1; t <= 3; t++) {
latest = new Snapshot(t, List.of("bat@" + t, "orc@" + (t * 2)));
}
});
logic.start();
logic.join();
Snapshot s = latest;
System.out.println("tick " + s.tick() + " " + s.enemies());
}
}tick 3 [bat@3, orc@6]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
צייד באגים: אויב נולד באמצע לולאהBug hunter: an enemy born mid-loop
תזכורת: מה ביקשוReminder: the task
כשה-orc "מוליד" תוך כדי המעבר על הרשימה, התוכנית קורסת. החליפו ל-CopyOnWriteArrayList (הלולאה עוברת על עותק) כך שיודפס [bat, orc, orc-baby].
When the orc "spawns" while the list is being looped over, the program crashes. Switch to a CopyOnWriteArrayList (the loop goes over a copy) so it prints [bat, orc, orc-baby].
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
count++ בתוך synchronizedcount++ inside synchronized
הפתרון המלא והפלט שלוFull solution and its output
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class Main {
public static void main(String[] args) {
List<String> enemies = new CopyOnWriteArrayList<>(List.of("bat", "orc"));
for (String e : enemies) {
if (e.equals("orc")) {
enemies.add("orc-baby");
}
}
System.out.println(enemies);
}
}[bat, orc, orc-baby]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
צעד זמן קבועA fixed timestep
תזכורת: מה ביקשוReminder: the task
צעד של 0.02 שנייה. זמני פריימים: 0.016, 0.033, 0.050, 0.016, 0.005. צוברים, ומריצים עדכון כל עוד הצטבר מספיק. הדפיסו את מספר העדכונים המצטבר אחרי כל פריים: 0 2 4 5 6.
A 0.02-second step. Frame times: 0.016, 0.033, 0.050, 0.016, 0.005. Accumulate, and run an update while enough has built up. Print the running number of updates after each frame: 0 2 4 5 6.
סימולציה: הפתרון רץ שורה אחרי שורהSimulation: the solution runs line by line
לוחצים הבא או נגן: רואים איזו שורה Java מבצעת, מה יש בכל קופסה (משתנה) ומה מופיע על המסך. זו הרצה אמיתית של הפתרון.
Press Next or Play: see which line Java runs, what is in each box (variable) and what appears on the screen. This is a real run of the solution.
צפו בהרצה צעד אחר צעדWatch it run, step by step
מה קורה עכשיוWhat happens now
הקופסאות (משתנים)The boxes (variables)
מסך הפלטOutput screen
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
public static void main(String[] args) {
double step = 0.02;
double acc = 0;
int updates = 0;
double[] frameTimes = {0.016, 0.033, 0.050, 0.016, 0.005};
for (double ft : frameTimes) {
acc += ft;
while (acc >= step) {
updates++;
acc -= step;
}
System.out.print(updates + " ");
}
System.out.println();
}
}0 2 4 5 6
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
שני חוצציםTwo buffers
תזכורת: מה ביקשוReminder: the task
הלוגיקה כותבת פריים לחוצץ האחורי ואז swap() (synchronized) מחליף. אחרי 3 פריימים החוצץ הקדמי: [30, 31, 32, 33].
The logic writes a frame to the back buffer then swap() (synchronized) exchanges them. After 3 frames the front buffer: [30, 31, 32, 33].
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
count++ בתוך synchronizedcount++ inside synchronized
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
static int[] front = new int[4];
static int[] back = new int[4];
static synchronized void swap() {
int[] t = front;
front = back;
back = t;
}
public static void main(String[] args) throws InterruptedException {
Thread logic = new Thread(() -> {
for (int frame = 1; frame <= 3; frame++) {
for (int i = 0; i < back.length; i++) {
back[i] = frame * 10 + i;
}
swap();
}
});
logic.start();
logic.join();
System.out.println(java.util.Arrays.toString(front));
}
}[30, 31, 32, 33]
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
משחק 5: עולם עם הרבה אויביםGame 5: a world with many enemies
תזכורת: מה ביקשוReminder: the task
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.
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
מה קורה בתוך thread poolWhat happens inside a thread pool
הפתרון המלא והפלט שלוFull solution and its output
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Main {
record Enemy(int id, int x) {
Enemy step() {
return new Enemy(id, x + id % 3 + 1);
}
}
public static void main(String[] args) throws Exception {
List<Enemy> world = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
world.add(new Enemy(i, 0));
}
ExecutorService pool = Executors.newFixedThreadPool(4);
for (int tick = 0; tick < 10; tick++) {
List<Future<List<Enemy>>> parts = new ArrayList<>();
int size = world.size() / 4;
for (int p = 0; p < 4; p++) {
List<Enemy> slice = world.subList(p * size, (p + 1) * size);
parts.add(pool.submit(() -> slice.stream().map(Enemy::step).toList()));
}
List<Enemy> next = new ArrayList<>();
for (Future<List<Enemy>> f : parts) {
next.addAll(f.get());
}
world = next;
}
pool.shutdown();
long far = world.stream().filter(e -> e.x() >= 30).count();
System.out.println(world.size() + " enemies, " + far + " reached x>=30, enemy 5 at x=" + world.get(5).x());
}
}1000 enemies, 333 reached x>=30, enemy 5 at x=30
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
לולאה מתוזמנתA scheduled loop
תזכורת: מה ביקשוReminder: the task
כתבו את הלולאה מהתזכורת: scheduleAtFixedRate כל 10ms, 105ms, ואז shutdown. מספר הטיקים המדויק משתנה, ולכן מדפיסים רק אם הוא סביב 10: about 10 ticks: true.
Write the loop from the refresher: scheduleAtFixedRate every 10ms, for 105ms, then shutdown. The exact tick count varies, so print only whether it's around 10: about 10 ticks: true.
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
מה קורה בתוך thread poolWhat happens inside a thread pool
הפתרון המלא והפלט שלוFull solution and its output
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
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
ניקוד מכמה threadsA score from several threads
תזכורת: מה ביקשוReminder: the task
שלושה threads מוסיפים כל אחד 5 נקודות 1000 פעמים ל-AtomicInteger. הדפיסו תמיד score 15000.
Three threads each add 5 points 1000 times to an AtomicInteger. Always print score 15000.
סימולציה: אתם מחליטים איזה thread רץSimulation: you decide which thread runs
כשיש כמה threads, אין "שורה הבאה" אחת: המתזמן בוחר. כאן אתם המתזמן, ואפשר גם לתת למזל לבחור 200 פעמים.
With several threads there's no single "next line": the scheduler picks. Here you're the scheduler, and you can also let chance pick 200 times.
AtomicInteger.incrementAndGetAtomicInteger.incrementAndGet
הפתרון המלא והפלט שלוFull solution and its output
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) throws InterruptedException {
AtomicInteger score = new AtomicInteger();
Thread[] spawners = new Thread[3];
for (int i = 0; i < spawners.length; i++) {
spawners[i] = new Thread(() -> {
for (int k = 0; k < 1000; k++) {
score.addAndGet(5);
}
});
spawners[i].start();
}
for (Thread t : spawners) {
t.join();
}
System.out.println("score " + score.get());
}
}score 15000
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.