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

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

ExecutorService, thread pools, Callable ו-FutureExecutorService, thread pools, Callable & Future

בריכת threads, משימות עם תוצאה, Future.get, invokeAll, וסגירה מסודרת.

Thread pools, tasks with a result, Future.get, invokeAll, and an orderly shutdown.

נסו לפתור לבד לפני שמציצים. בנגן: חיצים במקלדת או הכפתורים. כל צעד מראה איפה (קובץ ושורה), מה כותבים ולמה.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

סכום בארבעה חלקיםA sum in four parts

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

בריכה של 3 threads. ארבע משימות (Callable) סוכמות כל אחת 250 מספרים (1–250, 251–500 וכו'). אספו את ה-Futures, חברו, והדפיסו 500500.

A pool of 3 threads. Four tasks (Callables) each sum 250 numbers (1–250, 251–500 and so on). Collect the Futures, add, and print 500500.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.

מה קורה בתוך thread poolWhat happens inside a thread pool
הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        List<Future<Long>> parts = new ArrayList<>();
        for (int p = 0; p < 4; p++) {
            long from = p * 250L + 1;
            long to = from + 249;
            parts.add(pool.submit(() -> {
                long s = 0;
                for (long i = from; i <= to; i++) {
                    s += i;
                }
                return s;
            }));
        }
        long total = 0;
        for (Future<Long> f : parts) {
            total += f.get();
        }
        pool.shutdown();
        System.out.println(total);
    }
}
פלטOutput
500500

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

תרגילExercise 2

invokeAllinvokeAll

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

שלוש משימות מחזירות את אורך הכותר כמחרוזת. הריצו עם invokeAll על בריכה של 2 והדפיסו [4, 4, 7] (בסדר המשימות).

Three tasks return the title's length as a string. Run them with invokeAll on a pool of 2 and print [4, 4, 7] (in task order).

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.

מה קורה בתוך thread poolWhat happens inside a thread pool
הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        List<Callable<String>> jobs = List.of(() -> "Dune".length() + "", () -> "Emma".length() + "", () -> "Ulysses".length() + "");
        List<String> out = new ArrayList<>();
        for (Future<String> f : pool.invokeAll(jobs)) {
            out.add(f.get());
        }
        pool.shutdown();
        System.out.println(out);
    }
}
פלטOutput
[4, 4, 7]

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

תרגילExercise 3

צייד באגים: משימה שנכשלהBug hunter: a task that failed

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

המשימה מנסה להמיר 19x5 ונכשלת, ו-get() מפיל את main. תפסו את ExecutionException, הדפיסו task failed: NumberFormatException, וסגרו את הבריכה ב-finally.

The task tries to parse 19x5 and fails, and get() crashes main. Catch the ExecutionException, print task failed: NumberFormatException, and shut the pool in finally.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.

מה קורה בתוך thread poolWhat happens inside a thread pool
הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        Future<Integer> f = pool.submit(() -> Integer.parseInt("19x5"));
        try {
            System.out.println("year: " + f.get());
        } catch (java.util.concurrent.ExecutionException e) {
            System.out.println("task failed: " + e.getCause().getClass().getSimpleName());
        } finally {
            pool.shutdown();
        }
    }
}
פלטOutput
task failed: NumberFormatException

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

תרגילExercise 4

executor של thread אחדA single-thread executor

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

Executors.newSingleThreadExecutor() מריץ משימות אחת אחרי השנייה, לפי הסדר, ולכן ArrayList רגילה בטוחה כאן. שלחו open, read, close, סגרו, חכו, והדפיסו [open, read, close].

Executors.newSingleThreadExecutor() runs tasks one after another, in order, so a plain ArrayList is safe here. Submit open, read, close, shut down, wait, and print [open, read, close].

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.

מה קורה בתוך thread poolWhat happens inside a thread pool
הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newSingleThreadExecutor();
        List<String> log = new ArrayList<>();
        for (String step : List.of("open", "read", "close")) {
            pool.submit(() -> log.add(step));
        }
        pool.shutdown();
        pool.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println(log);
    }
}
פלטOutput
[open, read, close]

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

תרגילExercise 5

מדף, צעד 35: ייבוא מקביליShelf, step 35: a parallel import

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

כל שורה Title;Pages מיובאת במשימה משלה (importLine). הריצו עם invokeAll על בריכה של 2, אספו Bookים לפי הסדר, והדפיסו 4 books, 1865 pages, first Dune.

Each Title;Pages line is imported in its own task (importLine). Run them with invokeAll on a pool of 2, collect Books in order, and print 4 books, 1865 pages, first Dune.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.

מה קורה בתוך thread poolWhat happens inside a thread pool
הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Main {
    record Book(String title, int pages) {
    }

    static Book importLine(String line) {
        String[] f = line.split(";");
        return new Book(f[0], Integer.parseInt(f[1]));
    }

    public static void main(String[] args) throws Exception {
        List<String> lines = List.of("Dune;412", "Emma;474", "Ulysses;730", "Persuasion;249");
        ExecutorService pool = Executors.newFixedThreadPool(2);
        List<Callable<Book>> jobs = new ArrayList<>();
        for (String l : lines) {
            jobs.add(() -> importLine(l));
        }
        List<Book> books = new ArrayList<>();
        for (Future<Book> f : pool.invokeAll(jobs)) {
            books.add(f.get());
        }
        pool.shutdown();
        int pages = 0;
        for (Book b : books) {
            pages += b.pages();
        }
        System.out.println(books.size() + " books, " + pages + " pages, first " + books.get(0).title());
    }
}
פלטOutput
4 books, 1865 pages, first Dune

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

אתגרChallenge 1

זמן קצוב וביטולA timeout and a cancel

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

משימה איטית (2 שניות). get(100, MILLISECONDS) מוותר אחרי 100ms עם TimeoutException. בטלו עם cancel(true) והדפיסו too slow, cancelling: true ואז cancelled=true.

A slow task (2 seconds). get(100, MILLISECONDS) gives up after 100ms with a TimeoutException. Cancel with cancel(true) and print too slow, cancelling: true then cancelled=true.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.

מה קורה בתוך thread poolWhat happens inside a thread pool
הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(1);
        Future<String> slow = pool.submit(() -> {
            Thread.sleep(2000);
            return "done";
        });
        try {
            System.out.println(slow.get(100, TimeUnit.MILLISECONDS));
        } catch (java.util.concurrent.TimeoutException e) {
            System.out.println("too slow, cancelling: " + slow.cancel(true));
        }
        pool.shutdownNow();
        System.out.println("cancelled=" + slow.isCancelled());
    }
}
פלטOutput
too slow, cancelling: true
cancelled=true

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

אתגרChallenge 2

invokeAny: הראשון שמצליחinvokeAny: the first to succeed

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

שני "שרתי מראה" מחזירים ספר, אחד איטי ואחד מהיר. invokeAny מחזיר את התוצאה הראשונה ומבטל את השאר. הדפיסו got the book from the fast mirror.

Two "mirror servers" return a book, one slow and one fast. invokeAny returns the first result and cancels the rest. Print got the book from the fast mirror.

סרטון מונפש: על מה לוחצים, מה כותבים ולמה, צעד אחר צעד.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.

מה קורה בתוך thread poolWhat happens inside a thread pool
הפתרון המלא והפלט שלוFull solution and its output
Main.java
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Main {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        try {
            String first = pool.invokeAny(List.of(() -> {
                Thread.sleep(300);
                return "slow mirror";
            }, () -> "fast mirror"));
            System.out.println("got the book from the " + first);
        } finally {
            pool.shutdownNow();
        }
    }
}
פלטOutput
got the book from the fast mirror

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

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