נבנה על ידיBuilt by Ariel Yohimovich
JavaJava
Thread ללוגיקה ול-render, עם סנכרוןA thread for logic and rendering, with sync
מפגש 47: מפרידים את הלוגיקה מהציור ל-threads נפרדים, משתפים מצב בבטחה, ומשווים ל-Swing Timer.Session 47: Separating logic from drawing into their own threads, sharing state safely, and comparing with a Swing Timer.
מפרידים את הלוגיקה מהציור ל-threads נפרדים, משתפים מצב בבטחה, ומשווים ל-Swing Timer. בסוף המפגש מוסיפים צעד לפרויקט המלווה.Separating logic from drawing into their own threads, sharing state safely, and comparing with a Swing Timer. At the end we add a step to the companion project.מה נעשה היוםToday's plan
- מונחיםTerms
- לוגיקה ו-render, עם תמונת מצבLogic and render, with a snapshot
- טיימר במקום threadA timer instead of a thread
- טעויות נפוצותCommon mistakes
- פרויקט מדףShelf project
עוברים על סדר היום ומזכירים את הפרויקט המלווה.Walk through the plan and mention the companion project.המונחים של המפגשThis session's terms
- תמונת מצב: עותק בלתי משתנה של העולם (record עם
List.copyOf).snapshot: An immutable copy of the world (a record with List.copyOf). - צעד זמן קבוע: צוברים את זמן הפריימים, ומריצים עדכון של, נניח, 20ms בכל פעם שהצטבר מספיק.fixed timestep: Accumulate frame time, and run an update of, say, 20ms each time enough has built up.
- double buffering: שני חוצצים:double buffering: Two buffers:
- Event Dispatch Thread: ה-thread היחיד שמותר לו לגעת ברכיבי Swing.Event Dispatch Thread: The only thread allowed to touch Swing components.
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.Before the code, the words. Every term here is also linked in the course glossary.נושאTopic 2
לוגיקה ו-render, עם תמונת מצבLogic and render, with a snapshot
לוגיקה ו-render, עם תמונת מצבLogic and render, with a snapshot
- ה-thread של הלוגיקה בונה רשימת אויבים חדשה בכל טיק, ומפרסם תמונת מצב בלתי משתנה במשתנה volatile.The logic thread builds a new enemy list each tick, and publishes an immutable snapshot in a volatile variable.
- ה-render קורא את ההפניה פעם אחת ומצייר ממנה, ולכן אף פעם לא רואה עולם חצי מעודכן.The renderer reads the reference once and draws from it, so it never sees a half-updated world.
ה-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.נושאTopic 3
טיימר במקום threadA timer instead of a thread
טיימר במקום threadA timer instead of a thread
scheduleAtFixedRate מריץ טיק כל 10ms על thread אחד.scheduleAtFixedRate runs a tick every 10ms on one thread.- ב-Swing,
javax.swing.Timer עושה אותו דבר על ה-EDT, ואז אין שני threads ואין מה לסנכרן.In Swing, javax.swing.Timer does the same on the EDT, so there aren't two threads and nothing to synchronize.
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.נושאTopic 4
טעויות נפוצותCommon mistakes
טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says
java.util.ConcurrentModificationException:java.util.ConcurrentModificationException:
אלה הטעויות שהתרגילים מהסוג "צייד באגים" בנויים סביבן. כל אחת רצה באמת, והפלט הוא מה ש-Java עונה.These are the mistakes the "bug hunter" exercises are built around. Each one really runs, and the output is what Java says.נושאTopic 5
פרויקט מדףShelf project
הצעד של היום בפרויקט מדףToday's step in the Shelf project
- משחק 5: עולם עם הרבה אויביםGame 5: a world with many enemies
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.תמונת מצב: עותק בלתי משתנה של העולם (record עם List.copyOf).snapshot: An immutable copy of the world (a record with List.copyOf).
המונחים של המפגשThis session's termsצעד זמן קבוע: צוברים את זמן הפריימים, ומריצים עדכון של, נניח, 20ms בכל פעם שהצטבר מספיק.fixed timestep: Accumulate frame time, and run an update of, say, 20ms each time enough has built up.
המונחים של המפגשThis session's termsdouble buffering: שני חוצצים:double buffering: Two buffers:
המונחים של המפגשThis session's termsEvent Dispatch Thread: ה-thread היחיד שמותר לו לגעת ברכיבי Swing.Event Dispatch Thread: The only thread allowed to touch Swing components.
המונחים של המפגשThis session's termsה-thread של הלוגיקה בונה רשימת אויבים חדשה בכל טיק, ומפרסם תמונת מצב בלתי משתנה במשתנה volatile.The logic thread builds a new enemy list each tick, and publishes an immutable snapshot in a volatile variable.
לוגיקה ו-render, עם תמונת מצבLogic and render, with a snapshotה-render קורא את ההפניה פעם אחת ומצייר ממנה, ולכן אף פעם לא רואה עולם חצי מעודכן.The renderer reads the reference once and draws from it, so it never sees a half-updated world.
לוגיקה ו-render, עם תמונת מצבLogic and render, with a snapshotscheduleAtFixedRate מריץ טיק כל 10ms על thread אחד.scheduleAtFixedRate runs a tick every 10ms on one thread.
טיימר במקום threadA timer instead of a threadב-Swing, javax.swing.Timer עושה אותו דבר על ה-EDT, ואז אין שני threads ואין מה לסנכרן.In Swing, javax.swing.Timer does the same on the EDT, so there aren't two threads and nothing to synchronize.
טיימר במקום threadA timer instead of a threadjava.util.ConcurrentModificationException:java.util.ConcurrentModificationException:
טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java saysמשחק 5: עולם עם הרבה אויביםGame 5: a world with many enemies
הצעד של היום בפרויקט מדףToday's step in the Shelf projectלמה תמונת מצב בלתי משתנה בטוחה לשיתוף?Why is an immutable snapshot safe to share?
- כי אף אחד לא יכול לשנות אותה אחרי שפורסמהBecause nobody can change it after it's published
- כי היא קטנהBecause it's small
- כי Java נועלת אותהBecause Java locks it
- היא לא בטוחהIt isn't safe
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.כי אף אחד לא יכול לשנות אותה אחרי שפורסמהBecause nobody can change it after it's published
נכון.Right.איזה thread מותר לו לשנות רכיבי Swing?Which thread may change Swing components?
- ה-Event Dispatch ThreadThe Event Dispatch Thread
- כל threadAny thread
- mainmain
- thread של הלוגיקהThe logic thread
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.ה-Event Dispatch ThreadThe Event Dispatch Thread
נכון.Right.מה הבעיה עם עדכון x += speed פעם בפריים, בלי dt ובלי צעד קבוע?What's wrong with x += speed once per frame, with no dt and no fixed step?
- המהירות תלויה במספר הפריימים של המחשבThe speed depends on the computer's frame rate
- אין בעיהNo problem
- זה לא מתקמפלIt doesn't compile
- זה deadlockIt's a deadlock
שואלים את הכיתה ומצביעים. התשובה בשקופית הבאה.Ask the class and take a vote. The answer is on the next slide.המהירות תלויה במספר הפריימים של המחשבThe speed depends on the computer's frame rate
נכון.Right.פרסום תמונת מצבPublishing a snapshot
record Snapshot(int tick, List<String> enemies) ומשתנה static volatile Snapshot latest.record Snapshot(int tick, List<String> enemies) and a static volatile Snapshot latest.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.צייד באגים: אויב נולד באמצע לולאהBug hunter: an enemy born mid-loop
- כשה-orc "מוליד" תוך כדי המעבר על הרשימה, התוכנית קורסת.When the orc "spawns" while the list is being looped over, the program crashes.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.צעד זמן קבועA fixed timestep
- צעד של 0.02 שנייה.A 0.02-second step.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.שני חוצציםTwo buffers
- הלוגיקה כותבת פריים לחוצץ האחורי ואז
swap() (synchronized) מחליף.The logic writes a frame to the back buffer then swap() (synchronized) exchanges them.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.משחק 5: עולם עם הרבה אויביםGame 5: a world with many enemies
- 1000 אויבים.1000 enemies.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.לולאה מתוזמנתA scheduled loop
- כתבו את הלולאה מהתזכורת:Write the loop from the refresher:
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.ניקוד מכמה threadsA score from several threads
- שלושה threads מוסיפים כל אחד 5 נקודות 1000 פעמים ל-
AtomicInteger.Three threads each add 5 points 1000 times to an AtomicInteger.
תרגיל מהעמוד הבא: שואלים איך הייתם מתחילים.An exercise from the practice page: ask how you would start.בכל טיק latest = new Snapshot(...): הפניה חדשה, לא שינוי של הישנה.Each tick latest = new Snapshot(...): a new reference, not a change to the old one.
פרסום תמונת מצבPublishing a snapshotnew CopyOnWriteArrayList<>(...)new CopyOnWriteArrayList<>(...)
צייד באגים: אויב נולד באמצע לולאהBug hunter: an enemy born mid-loopwhile (acc >= step) { updates++; acc -= step; }while (acc >= step) { updates++; acc -= step; }
צעד זמן קבועA fixed timestepמחליפים הפניות, לא מעתיקים.Swap references, don't copy.
שני חוצציםTwo buffersעצמים בלתי משתנים + עולם חדש בכל טיק = בלי מרוצים.Immutable objects + a new world each tick = no races.
משחק 5: עולם עם הרבה אויביםGame 5: a world with many enemiesמה למדנוWhat we learned
- תמונת מצב: עותק בלתי משתנה של העולם (record עם
List.copyOf).snapshot: An immutable copy of the world (a record with List.copyOf). - ה-thread של הלוגיקה בונה רשימת אויבים חדשה בכל טיק, ומפרסם תמונת מצב בלתי משתנה במשתנה volatile.The logic thread builds a new enemy list each tick, and publishes an immutable snapshot in a volatile variable.
scheduleAtFixedRate מריץ טיק כל 10ms על thread אחד.scheduleAtFixedRate runs a tick every 10ms on one thread.java.util.ConcurrentModificationException:java.util.ConcurrentModificationException:- משחק 5: עולם עם הרבה אויביםGame 5: a world with many enemies
כל אחד אומר דבר אחד שלמד היום.Everyone says one thing they learned today.עכשיו לתרגולNow, practice
5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
מפנים לעמוד התרגול.Point to the practice page.