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

JavaJava
31
חלקPart 6: Concurrency ו-ThreadsConcurrency & threads כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

Thread ו-Runnable, start מול run, ו-joinThread & Runnable, start vs run, and join

מה זה thread, יצירה עם Runnable ולמבדה, ההבדל בין start ל-run, join, ומצבי ה-thread.

What a thread is, creating one with Runnable and lambdas, the difference between start and run, join, and thread states.

01המונחים של המפגשThis session's terms

לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.

Before the code, the words. Every term here is also linked in the course glossary.

  • thread: "קו ביצוע" בתוך תוכנית. לכל thread יש stack משלו, אבל כולם חולקים את ה-heap. main הוא thread בעצמו.thread: A "line of execution" inside a program. Each thread has its own stack, but they all share the heap. main is a thread itself.
  • Runnable: functional interface עם void run(): העבודה שה-thread יעשה. new Thread(() -> ...) מקבל אותה כלמבדה.Runnable: A functional interface with void run(): the work the thread will do. new Thread(() -> ...) takes it as a lambda.
  • start מול run: start() יוצר thread חדש שמריץ את run(). קריאה ישירה ל-run() היא סתם קריאה למתודה, באותו thread.start vs run: start() creates a new thread that runs run(). Calling run() directly is just a method call, on the same thread.
  • join: t.join() עוצר את ה-thread הנוכחי עד ש-t מסיים. זה גם מבטיח שכל מה ש-t כתב נראה אחרי ה-join.join: t.join() stops the current thread until t finishes. It also guarantees that whatever t wrote is visible after the join.
  • מצבי thread: NEW (נוצר), RUNNABLE (רץ או מוכן), BLOCKED/WAITING/TIMED_WAITING (מחכה), TERMINATED (סיים). getState() מחזיר אותו.thread states: NEW (created), RUNNABLE (running or ready), BLOCKED/WAITING/TIMED_WAITING (waiting), TERMINATED (done). getState() returns it.
  • מתזמן: החלק במערכת ההפעלה שמחליט איזה thread רץ עכשיו ולכמה זמן. ההחלטות שלו לא צפויות, ולכן הסדר בין threads משתנה בין הרצות.scheduler: The part of the OS deciding which thread runs now and for how long. Its decisions are unpredictable, so the order between threads changes between runs.

02שני threads, סדר לא ידועTwo threads, an unknown order

start() מפעיל כל thread, ו-join() מחכה לו. השורה main is done תמיד אחרונה, אבל A ו-B יכולים להתחלף. הרצנו את התוכנית באמת 20 פעמים בזמן הבנייה: הטבלה מראה מה יצא. בסימולטור אתם המתזמן.

start() launches each thread, and join() waits for it. main is done is always last, but A and B can swap. We really ran the program 20 times while building the site: the table shows what came out. In the simulator you're the scheduler.

Main.java
public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread a = new Thread(() -> System.out.println("A says hi"));
        Thread b = new Thread(() -> System.out.println("B says hi"));
        a.start();
        b.start();
        a.join();
        b.join();
        System.out.println("main is done");
    }
}
פלטOutput הסדר יכול להשתנות בין הרצותThe order can change between runs
A says hi
B says hi
main is done

20 הרצות אמיתיות בזמן בניית האתר (JDK 21):20 real runs while building the site (JDK 21):

הפלטOutputכמה פעמיםTimes
A says hi B says hi main is done19
B says hi A says hi main is done1
start ו-joinstart and join

03start מול runstart vs run

t.run() רץ ב-main עצמו, כמו כל קריאה למתודה. רק t.start() יוצר thread חדש בשם worker. הפלט כאן קבוע, כי join מחכה.

t.run() runs on main itself, like any method call. Only t.start() creates a new thread named worker. The output here is fixed, because join waits.

Main.java
public class Main {
    public static void main(String[] args) throws InterruptedException {
        Runnable job = () -> System.out.println("running in " + Thread.currentThread().getName());
        Thread t = new Thread(job, "worker");
        t.run();
        t.start();
        t.join();
    }
}
פלטOutput הסדר יכול להשתנות בין הרצותThe order can change between runs
running in main
running in worker
start ו-joinstart and join

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

כתבו שני קבצים (fiction.txt עם 3 ספרים, poetry.txt עם 2). Loader implements Runnable קורא קובץ לתוך רשימה משלו. הפעילו שני טוענים במקביל, חכו, והדפיסו Loaded 5 books from 2 files.

Write two files (fiction.txt with 3 books, poetry.txt with 2). Loader implements Runnable reads a file into its own list. Start two loaders at once, wait, and print Loaded 5 books from 2 files.

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

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.

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