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.
01המונחים של המפגשThis session's terms
לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.
Before the code, the words. Every term here is also linked in the course glossary.
- wait ו-notify:
lock.wait()משחרר את המנעול ונרדם עד ש-lock.notifyAll()מעיר אותו (ואז הוא מחכה לקבל את המנעול שוב). שניהם רק בתוךsynchronized (lock).wait and notify:lock.wait()releases the lock and sleeps untillock.notifyAll()wakes it (then it waits to get the lock back). Both only insidesynchronized (lock). - התעוררות שקרית: thread יכול להתעורר מ-wait בלי סיבה, או אחרי שמישהו אחר כבר לקח את מה שחיכה לו. לכן בודקים את התנאי ב-
while, לא ב-if.spurious wakeup: A thread can wake from wait for no reason, or after someone else already took what it waited for. That's why the condition is checked in awhile, not anif. - יצרן-צרכן: thread אחד (או יותר) מייצר עבודה ושם בתור, ואחרים לוקחים ומעבדים. התור מאזן בין המהירויות.producer-consumer: One thread (or more) produces work into a queue, and others take and process it. The queue balances the speeds.
- BlockingQueue: תור בטוח ל-threads:
putמחכה כשהוא מלא,takeמחכה כשהוא ריק.ArrayBlockingQueue(גודל קבוע),LinkedBlockingQueue.BlockingQueue: A thread-safe queue:putwaits when it's full,takewaits when it's empty.ArrayBlockingQueue(fixed size),LinkedBlockingQueue. - גלולת רעל: ערך מיוחד שהיצרן שם בתור כדי לומר לצרכן "זהו, אפשר לסיים". אחד לכל צרכן.poison pill: A special value the producer puts in the queue to tell a consumer "that's it, you can stop". One per consumer.
02wait ו-notifyAllwait and notifyAll
הצרכן נועל, ובודק ב-while אם יש חבילה. אין? wait() משחרר את המנעול ונרדם. main שם חבילה ו-notifyAll(). הצרכן מתעורר, מקבל שוב את המנעול, בודק שוב, ומדפיס.
The consumer locks, and checks in a while whether there's a parcel. None? wait() releases the lock and sleeps. main puts a parcel and calls notifyAll(). The consumer wakes, gets the lock back, checks again, and prints.
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 = "Dune";
lock.notifyAll();
}
consumer.join();
}
}got Dune
5 הרצות אמיתיות בזמן בניית האתר (JDK 21):5 real runs while building the site (JDK 21):
| הפלטOutput | כמה פעמיםTimes |
|---|---|
got Dune | 5 |
wait ו-notify עם תנאי בלולאהwait and notify with a condition in a loop
wait בלי לבדוק תנאי: notify שהלך לאיבודwait without a condition: a lost notify
03BlockingQueue: אותו דבר, בלי waitBlockingQueue: the same, without wait
ArrayBlockingQueue בגודל 2: היצרן נחסם כשהתור מלא, והצרכן נחסם כשהוא ריק. הסדר processed 1..5 מובטח, כי זה תור.
An ArrayBlockingQueue of size 2: the producer blocks when the queue is full, the consumer blocks when it's empty. The order processed 1..5 is guaranteed, because it's a queue.
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<>(2);
Thread producer = new Thread(() -> {
try {
for (int i = 1; i <= 5; i++) {
queue.put(i);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
Thread consumer = new Thread(() -> {
try {
for (int i = 1; i <= 5; 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 processed 4 processed 5
5 הרצות אמיתיות בזמן בניית האתר (JDK 21):5 real runs while building the site (JDK 21):
| הפלטOutput | כמה פעמיםTimes |
|---|---|
processed 1
processed 2
processed 3
processed 4
processed 5 | 5 |
BlockingQueue: יצרן וצרכןBlockingQueue: producer and consumer
04הצעד של היום בפרויקט מדףToday's step in the Shelf project
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}.
את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.
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.