נבנה על ידי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.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.Try on your own before peeking. In the player use the arrow keys or the buttons. Each step shows where (file and line), what to write, and why.
תרגילExercise 1

שני דובריםTwo speakers

תזכורת: מה ביקשוReminder: the task

שני threads: אחד מדפיס Noa 1 עד Noa 3, השני Avi 1 עד Avi 3 (מתודה say(name)). חכו לשניהם עם join והדפיסו done. הסדר בין Noa ל-Avi יכול להשתנות, אבל done תמיד אחרון.

Two threads: one prints Noa 1 to Noa 3, the other Avi 1 to Avi 3 (a say(name) method). Wait for both with join and print done. The order between Noa and Avi can change, but done is always last.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה 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.

start ו-joinstart and join
הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread a = new Thread(() -> say("Noa"));
        Thread b = new Thread(() -> say("Avi"));
        a.start();
        b.start();
        a.join();
        b.join();
        System.out.println("done");
    }

    static void say(String name) {
        for (int i = 1; i <= 3; i++) {
            System.out.println(name + " " + i);
        }
    }
}
פלטOutput הסדר יכול להשתנות בין הרצותThe order can change between runs
Noa 1
Noa 2
Noa 3
Avi 1
Avi 2
Avi 3
done

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 2

סכום בשני חצאיםA sum in two halves

תזכורת: מה ביקשוReminder: the task

Summer implements Runnable סוכם קטע של מערך לתוך שדה sum משלו. שני threads סוכמים את 1–50 ואת 51–100. אחרי join הדפיסו 1275 + 3775 = 5050.

Summer implements Runnable sums a slice of an array into its own sum field. Two threads sum 1–50 and 51–100. After join print 1275 + 3775 = 5050.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה 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.

start ו-joinstart and join
הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) throws InterruptedException {
        int[] nums = new int[100];
        for (int i = 0; i < nums.length; i++) {
            nums[i] = i + 1;
        }
        Summer left = new Summer(nums, 0, 50);
        Summer right = new Summer(nums, 50, 100);
        Thread t1 = new Thread(left);
        Thread t2 = new Thread(right);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(left.sum + " + " + right.sum + " = " + (left.sum + right.sum));
    }
}

class Summer implements Runnable {
    private final int[] nums;
    private final int from;
    private final int to;
    long sum;

    Summer(int[] nums, int from, int to) {
        this.nums = nums;
        this.from = from;
        this.to = to;
    }

    @Override
    public void run() {
        for (int i = from; i < to; i++) {
            sum += nums[i];
        }
    }
}
פלטOutput
1275 + 3775 = 5050

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 3

צייד באגים: run במקום startBug hunter: run instead of start

תזכורת: מה ביקשוReminder: the task

התוכנית מדפיסה loading in main פעמיים: שום thread חדש לא נוצר. תקנו כך שכל טוען ירוץ ב-thread שלו (Loader-1, Loader-2), וחכו לשניהם.

The program prints loading in main twice: no new thread was created. Fix it so each loader runs on its own thread (Loader-1, Loader-2), and wait for both.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה 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.

start ו-joinstart and join
הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread a = new Thread(() -> System.out.println("loading in " + Thread.currentThread().getName()), "Loader-1");
        Thread b = new Thread(() -> System.out.println("loading in " + Thread.currentThread().getName()), "Loader-2");
        a.start();
        b.start();
        a.join();
        b.join();
    }
}
פלטOutput הסדר יכול להשתנות בין הרצותThe order can change between runs
loading in Loader-2
loading in Loader-1

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 4

צייד באגים: לא חיכינוBug hunter: we didn't wait

תזכורת: מה ביקשוReminder: the task

התוכנית מדפיסה בדרך כלל Loaded 0 books: main קורא את המונה לפני שהטוען סיים. הוסיפו את מה שחסר כך שיודפס תמיד Loaded 3 books.

The program usually prints Loaded 0 books: main reads the counter before the loader finished. Add what's missing so it always prints Loaded 3 books.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה 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.

start ו-joinstart and join
הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    static int loaded = 0;

    public static void main(String[] args) throws InterruptedException {
        Thread loader = new Thread(() -> {
            for (String title : new String[]{"Dune", "Emma", "Ulysses"}) {
                loaded++;
            }
        });
        loader.start();
        loader.join();
        System.out.println("Loaded " + loaded + " books");
    }
}
פלטOutput
Loaded 3 books

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

תרגילExercise 5

מדף, צעד 31: טעינת שני קבצים במקבילShelf, step 31: loading two files at once

תזכורת: מה ביקשוReminder: the task

כתבו שני קבצים (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.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה 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.

start ו-joinstart and join
הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class Main {
    public static void main(String[] args) throws Exception {
        Files.write(Path.of("fiction.txt"), List.of("Dune", "Emma", "Ulysses"));
        Files.write(Path.of("poetry.txt"), List.of("Odyssey", "Leaves of Grass"));
        Loader a = new Loader(Path.of("fiction.txt"));
        Loader b = new Loader(Path.of("poetry.txt"));
        Thread ta = new Thread(a);
        Thread tb = new Thread(b);
        ta.start();
        tb.start();
        ta.join();
        tb.join();
        System.out.println("Loaded " + (a.books.size() + b.books.size()) + " books from 2 files");
    }
}

class Loader implements Runnable {
    private final Path file;
    List<String> books = List.of();

    Loader(Path file) {
        this.file = file;
    }

    @Override
    public void run() {
        try {
            books = Files.readAllLines(file);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}
פלטOutput
Loaded 5 books from 2 files

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 1

מצבי threadThread states

תזכורת: מה ביקשוReminder: the task

הדפיסו את המצב של thread לפני start (NEW), ואחרי join (TERMINATED alive=false). באמצע ה-thread מדפיס working.

Print a thread's state before start (NEW), and after join (TERMINATED alive=false). In between the thread prints working.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה 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.

start ו-joinstart and join
הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(() -> System.out.println("working"), "w");
        System.out.println(t.getState());
        t.start();
        t.join();
        System.out.println(t.getState() + " alive=" + t.isAlive());
    }
}
פלטOutput
NEW
working
TERMINATED alive=false

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

אתגרChallenge 2

מקסימום בארבעה threadsA maximum on four threads

תזכורת: מה ביקשוReminder: the task

חלקו מערך של 8 מספרים ל-4 חלקים. כל thread מוצא את המקסימום בחלק שלו וכותב לתא משלו במערך best. אחרי join לכולם, הדפיסו [42, 19, 88, 61] -> 88.

Split an 8-number array into 4 parts. Each thread finds its part's maximum and writes to its own cell of a best array. After joining them all, print [42, 19, 88, 61] -> 88.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.An animated movie: what to click, what to type and why, step by step.
איפהWhere
מהWhat
למהWhy

סימולציה: אתם מחליטים איזה 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.

start ו-joinstart and join
הפתרון המלא והפלט שלוFull solution and its output
Main.java
public class Main {
    public static void main(String[] args) throws InterruptedException {
        int[] data = {7, 42, 3, 19, 88, 5, 61, 12};
        int parts = 4;
        int[] best = new int[parts];
        Thread[] workers = new Thread[parts];
        int size = data.length / parts;
        for (int p = 0; p < parts; p++) {
            int from = p * size;
            int slot = p;
            workers[p] = new Thread(() -> {
                int m = data[from];
                for (int i = from; i < from + size; i++) {
                    m = Math.max(m, data[i]);
                }
                best[slot] = m;
            });
            workers[p].start();
        }
        for (Thread w : workers) {
            w.join();
        }
        int max = best[0];
        for (int m : best) {
            max = Math.max(max, m);
        }
        System.out.println(java.util.Arrays.toString(best) + " -> " + max);
    }
}
פלטOutput
[42, 19, 88, 61] -> 88

יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.

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