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

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

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.

כותבים בעורך שבכל תרגיל, לוחצים הרצה כדי לראות פלט, ובדיקה כדי שהבודק האוטומטי יבדוק. אפשר גם לעבוד ב-IntelliJ ולסמן פתרתי. ההתקדמות נשמרת.Write in each exercise's editor, press Run to see output and Check for the automatic checker. You can also work in IntelliJ and mark I solved it. Progress is saved.

חימום: 3 שאלותWarm-up: 3 questions

1. למה בודקים את התנאי של wait ב-while ולא ב-if?Why check wait's condition in a while and not an if?

2. מה עושה wait() עם המנעול?What does wait() do with the lock?

3. מה עושה take() על BlockingQueue ריק?What does take() do on an empty BlockingQueue?

תרגיליםExercises

תרגילExercise 1

מחכים לחבילהWaiting for a parcel

כתבו את הצרכן מהתזכורת: נועל, 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.

איך הפלט אמור להיראות?What should the output look like?
got Emma
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: wait ו-notifyAll רק בתוך synchronized (lock), אחרת IllegalMonitorStateException.wait and notifyAll only inside synchronized (lock), or you get IllegalMonitorStateException.
לפתרוןSolution
תרגילExercise 2

תור חסום בעצמכםA bounded queue of your own

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.

איך הפלט אמור להיראות?What should the output look like?
sum 10
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: while (items.size() == cap) wait();while (items.size() == cap) wait();
לפתרוןSolution
תרגילExercise 3

צייד באגים: notify שהלך לאיבודBug hunter: a lost notify

כאן ה-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!.

איך הפלט אמור להיראות?What should the output look like?
ready!
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: עם while, אם ready כבר true, לא מחכים בכלל.With while, if ready is already true, you don't wait at all.
לפתרוןSolution
תרגילExercise 4

תור בגודל 1A queue of size 1

שנו את הדוגמה מהתזכורת לתור בגודל 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.

איך הפלט אמור להיראות?What should the output look like?
processed 1
processed 2
processed 3
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: new ArrayBlockingQueue<>(1)new ArrayBlockingQueue<>(1)
לפתרוןSolution
תרגילExercise 5

מדף, צעד 34: תור ייבואShelf, step 34: an import queue

פרויקט מלווהCompanion 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}.

איך הפלט אמור להיראות?What should the output look like?
{Austen=2, Herbert=2, Joyce=1}
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: גלולת רעל לכל צרכן, אחרת אחד מהם יחכה לנצח.A poison pill per consumer, otherwise one of them waits forever.
לפתרוןSolution

אתגרים לחזקיםChallenges for the brave

אתגרChallenge 1

CountDownLatchCountDownLatch

שלושה טוענים מדפיסים 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.

איך הפלט אמור להיראות?What should the output look like?
loader 3 ready
loader 1 ready
loader 2 ready
all loaders ready, count=0
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: new CountDownLatch(3)new CountDownLatch(3)
לפתרוןSolution
אתגרChallenge 2

poll עם זמן קצובpoll with a timeout

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.

איך הפלט אמור להיראות?What should the output look like?
first: null
second: Dune
Main.java
ההשוואה נעשית בדפדפן מול הפלט האמיתי של הפתרון שלנו. אם הקוד נפל, הדביקו את הודעת השגיאה ותקבלו הסבר.The comparison happens in your browser, against our solution's real output. If the code crashed, paste the error message and get an explanation.
רמזHint 1: זמן קצוב מונע מצרכן להיתקע לנצח.A timeout stops a consumer from getting stuck forever.
לפתרוןSolution

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