נבנה על ידיBuilt by Ariel Yohimovich

חזרה למפגשBack
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.

מה נעשה היוםToday's plan

  • מונחיםTerms
  • לוגיקה ו-render, עם תמונת מצבLogic and render, with a snapshot
  • טיימר במקום threadA timer instead of a thread
  • טעויות נפוצותCommon mistakes
  • פרויקט מדףShelf project
נושאTopic 1

מונחיםTerms

המונחים של המפגש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.
נושא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.
נושא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.
נושאTopic 4

טעויות נפוצותCommon mistakes

טעויות נפוצות, ומה Java עונהCommon mistakes, and what Java says

  • java.util.ConcurrentModificationException:java.util.ConcurrentModificationException:
נושאTopic 5

פרויקט מדףShelf project

הצעד של היום בפרויקט מדףToday's step in the Shelf project

  • משחק 5: עולם עם הרבה אויביםGame 5: a world with many enemies

תמונת מצב: עותק בלתי משתנה של העולם (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.

ה-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.

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.

java.util.ConcurrentModificationException:java.util.ConcurrentModificationException:

משחק 5: עולם עם הרבה אויביםGame 5: a world with many enemies

למה תמונת מצב בלתי משתנה בטוחה לשיתוף?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

כי אף אחד לא יכול לשנות אותה אחרי שפורסמהBecause nobody can change it after it's published

איזה thread מותר לו לשנות רכיבי Swing?Which thread may change Swing components?

  • ה-Event Dispatch ThreadThe Event Dispatch Thread
  • כל threadAny thread
  • mainmain
  • thread של הלוגיקהThe logic thread

ה-Event Dispatch ThreadThe Event Dispatch Thread

מה הבעיה עם עדכון 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

המהירות תלויה במספר הפריימים של המחשבThe speed depends on the computer's frame rate

פרסום תמונת מצב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.

צייד באגים: אויב נולד באמצע לולאהBug hunter: an enemy born mid-loop

  • כשה-orc "מוליד" תוך כדי המעבר על הרשימה, התוכנית קורסת.When the orc "spawns" while the list is being looped over, the program crashes.

צעד זמן קבועA fixed timestep

  • צעד של 0.02 שנייה.A 0.02-second step.

שני חוצציםTwo buffers

  • הלוגיקה כותבת פריים לחוצץ האחורי ואז swap() (synchronized) מחליף.The logic writes a frame to the back buffer then swap() (synchronized) exchanges them.

משחק 5: עולם עם הרבה אויביםGame 5: a world with many enemies

  • 1000 אויבים.1000 enemies.

לולאה מתוזמנתA scheduled loop

  • כתבו את הלולאה מהתזכורת:Write the loop from the refresher:

ניקוד מכמה threadsA score from several threads

  • שלושה threads מוסיפים כל אחד 5 נקודות 1000 פעמים ל-AtomicInteger.Three threads each add 5 points 1000 times to an AtomicInteger.

בכל טיק latest = new Snapshot(...): הפניה חדשה, לא שינוי של הישנה.Each tick latest = new Snapshot(...): a new reference, not a change to the old one.

new CopyOnWriteArrayList<>(...)new CopyOnWriteArrayList<>(...)

while (acc >= step) { updates++; acc -= step; }while (acc >= step) { updates++; acc -= step; }

מחליפים הפניות, לא מעתיקים.Swap references, don't copy.

עצמים בלתי משתנים + עולם חדש בכל טיק = בלי מרוצים.Immutable objects + a new world each tick = no races.

מה למדנו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

עכשיו לתרגולNow, practice

5 תרגילים ו-2 אתגרים, עם בדיקה אוטומטית5 exercises and 2 challenges, auto-checked
הערות מרצהSpeaker notes

נבנה על ידיBuilt by Ariel Yohimovich