wait/notify, producer/consumer ו-BlockingQueuewait/notify, producer/consumer & BlockingQueue
המתנה לתנאי עם wait ו-notify, תבנית יצרן-צרכן, ו-BlockingQueue שעושה את זה בשבילכם.
Waiting for a condition with wait and notify, the producer-consumer pattern, and BlockingQueue that does it for you.
מחכים לחבילהWaiting for a parcel
תזכורת: מה ביקשוReminder: the task
כתבו את הצרכן מהתזכורת: נועל, while (parcel == null) lock.wait(), ומדפיס got Emma. main ישן 20ms, שם Emma וקורא ל-notifyAll() בתוך אותו מנעול.
Write the consumer from the refresher: lock, while (parcel == null) lock.wait(), and print got Emma. main sleeps 20ms, puts Emma and calls notifyAll() inside the same lock.
סימולציה: אתם מחליטים איזה 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.
wait ו-notify עם תנאי בלולאהwait and notify with a condition in a loop
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
private static final Object lock = new Object();
private static String parcel = null;
public static void main(String[] args) throws InterruptedException {
Thread consumer = new Thread(() -> {
synchronized (lock) {
while (parcel == null) {
try {
lock.wait();
} catch (InterruptedException e) {
return;
}
}
System.out.println("got " + parcel);
}
});
consumer.start();
Thread.sleep(20);
synchronized (lock) {
parcel = "Emma";
lock.notifyAll();
}
consumer.join();
}
}got Emma
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
תור חסום בעצמכםA bounded queue of your own
תזכורת: מה ביקשוReminder: the task
Box בגודל 2 עם synchronized put (מחכה כשמלא) ו-synchronized take (מחכה כשריק), שתיהן קוראות ל-notifyAll() אחרי שינוי. יצרן שם 1–4, צרכן סוכם. הדפיסו sum 10.
Box of size 2 with a synchronized put (waits when full) and a synchronized take (waits when empty), both calling notifyAll() after a change. A producer puts 1–4, a consumer sums. Print sum 10.
סימולציה: אתם מחליטים איזה 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.
BlockingQueue: יצרן וצרכןBlockingQueue: producer and consumer
הפתרון המלא והפלט שלוFull solution and its output
import java.util.ArrayDeque;
import java.util.Deque;
public class Main {
public static void main(String[] args) throws InterruptedException {
Box box = new Box(2);
Thread producer = new Thread(() -> {
for (int i = 1; i <= 4; i++) {
box.put(i);
}
});
Thread consumer = new Thread(() -> {
int sum = 0;
for (int i = 1; i <= 4; i++) {
sum += box.take();
}
System.out.println("sum " + sum);
});
producer.start();
consumer.start();
producer.join();
consumer.join();
}
}
class Box {
private final Deque<Integer> items = new ArrayDeque<>();
private final int cap;
Box(int cap) {
this.cap = cap;
}
synchronized void put(int x) {
while (items.size() == cap) {
try {
wait();
} catch (InterruptedException e) {
return;
}
}
items.add(x);
notifyAll();
}
synchronized int take() {
while (items.isEmpty()) {
try {
wait();
} catch (InterruptedException e) {
return -1;
}
}
int x = items.poll();
notifyAll();
return x;
}
}sum 10
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
צייד באגים: notify שהלך לאיבודBug hunter: a lost notify
תזכורת: מה ביקשוReminder: the task
כאן ה-notify נשלח לפני שה-waiter בכלל התחיל, וה-waiter קורא ל-wait() בלי לבדוק תנאי: הוא יחכה לנצח (נסו: התוכנית נתקעת). תקנו עם while (!ready) lock.wait(); כך שתמיד יודפס ready!.
Here the notify is sent before the waiter even started, and the waiter calls wait() without checking a condition: it waits forever (try it: the program hangs). Fix it with while (!ready) lock.wait(); so it always prints ready!.
סימולציה: אתם מחליטים איזה 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.
wait בלי לבדוק תנאי: notify שהלך לאיבודwait without a condition: a lost notify
wait ו-notify עם תנאי בלולאהwait and notify with a condition in a loop
הפתרון המלא והפלט שלוFull solution and its output
public class Main {
private static final Object lock = new Object();
private static boolean ready = false;
public static void main(String[] args) throws InterruptedException {
Thread waiter = new Thread(() -> {
synchronized (lock) {
while (!ready) {
try {
lock.wait();
} catch (InterruptedException e) {
return;
}
}
System.out.println("ready!");
}
});
synchronized (lock) {
ready = true;
lock.notifyAll();
}
waiter.start();
waiter.join();
}
}ready!
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
תור בגודל 1A queue of size 1
תזכורת: מה ביקשוReminder: the task
שנו את הדוגמה מהתזכורת לתור בגודל 1 ושלושה פריטים. היצרן נחסם אחרי כל פריט עד שהצרכן לוקח. הפלט עדיין processed 1, processed 2, processed 3.
Change the refresher example to a queue of size 1 and three items. The producer blocks after each item until the consumer takes it. The output is still processed 1, processed 2, processed 3.
סימולציה: אתם מחליטים איזה 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.
BlockingQueue: יצרן וצרכןBlockingQueue: producer and consumer
הפתרון המלא והפלט שלוFull solution and its output
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class Main {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(1);
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 3; i++) {
queue.put(i);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
Thread consumer = new Thread(() -> {
try {
for (int i = 1; i <= 3; i++) {
System.out.println("processed " + queue.take());
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
producer.start();
consumer.start();
producer.join();
consumer.join();
}
}processed 1 processed 2 processed 3
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
מדף, צעד 34: תור ייבואShelf, step 34: an import queue
תזכורת: מה ביקשוReminder: the task
main (הקורא) שם שורות Title;Author ב-LinkedBlockingQueue. שני מעבדים לוקחים שורות וסופרים ספרים לפי סופר במפה משותפת (מוגנת). בסוף main שם <done> פעמיים (אחד לכל מעבד). הדפיסו {Austen=2, Herbert=2, Joyce=1}.
main (the reader) puts Title;Author lines into a LinkedBlockingQueue. Two processors take lines and count books per author in a shared (protected) map. At the end main puts <done> twice (one per processor). Print {Austen=2, Herbert=2, Joyce=1}.
סימולציה: אתם מחליטים איזה 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.
BlockingQueue: יצרן וצרכןBlockingQueue: producer and consumer
הפתרון המלא והפלט שלוFull solution and its output
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class Main {
static final String DONE = "<done>";
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> lines = new LinkedBlockingQueue<>();
Map<String, Integer> byAuthor = new TreeMap<>();
Runnable processor = () -> {
try {
while (true) {
String line = lines.take();
if (line.equals(DONE)) {
return;
}
String author = line.split(";")[1];
synchronized (byAuthor) {
byAuthor.merge(author, 1, Integer::sum);
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
};
Thread p1 = new Thread(processor);
Thread p2 = new Thread(processor);
p1.start();
p2.start();
for (String l : List.of("Emma;Austen", "Dune;Herbert", "Persuasion;Austen", "Ulysses;Joyce", "Children of Dune;Herbert")) {
lines.put(l);
}
lines.put(DONE);
lines.put(DONE);
p1.join();
p2.join();
System.out.println(byAuthor);
}
}{Austen=2, Herbert=2, Joyce=1}יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
CountDownLatchCountDownLatch
תזכורת: מה ביקשוReminder: the task
שלושה טוענים מדפיסים loader N ready וקוראים ל-countDown(). main מחכה עם await() ומדפיס all loaders ready, count=0. סדר הטוענים משתנה, אבל השורה של main תמיד אחרונה.
Three loaders print loader N ready and call countDown(). main waits with await() and prints all loaders ready, count=0. The loaders' order changes, but main's line is always last.
סימולציה: אתם מחליטים איזה 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
import java.util.concurrent.CountDownLatch;
public class Main {
public static void main(String[] args) throws InterruptedException {
CountDownLatch ready = new CountDownLatch(3);
for (int i = 1; i <= 3; i++) {
int id = i;
new Thread(() -> {
System.out.println("loader " + id + " ready");
ready.countDown();
}).start();
}
ready.await();
System.out.println("all loaders ready, count=" + ready.getCount());
}
}loader 3 ready loader 1 ready loader 2 ready all loaders ready, count=0
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.
poll עם זמן קצובpoll with a timeout
תזכורת: מה ביקשוReminder: the task
q.poll(50, TimeUnit.MILLISECONDS) מחכה עד 50ms ומחזיר null אם לא הגיע כלום. הדפיסו first: null, הוסיפו Dune עם offer, והדפיסו second: Dune.
q.poll(50, TimeUnit.MILLISECONDS) waits up to 50ms and returns null if nothing came. Print first: null, add Dune with offer, and print second: Dune.
סימולציה: אתם מחליטים איזה 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.
BlockingQueue: יצרן וצרכןBlockingQueue: producer and consumer
הפתרון המלא והפלט שלוFull solution and its output
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> q = new LinkedBlockingQueue<>();
String first = q.poll(50, TimeUnit.MILLISECONDS);
System.out.println("first: " + first);
q.offer("Dune");
String second = q.poll(50, TimeUnit.MILLISECONDS);
System.out.println("second: " + second);
}
}first: null second: Dune
יש יותר מדרך נכונה אחת. אם הפלט שלכם זהה, גם הפתרון שלכם נכון.There is more than one right way. If your output matches, your solution is right too.