Saturday, August 28, 2010

Multithreading: Waiting.java

Courtesy of Sun Web Learning Center



 1. class Waiting implements Runnable {
 2.   boolean flag = false;
 3.   public synchronized void run() {
 4.     if (flag) {
 5.       flag = false;
 6.       System.out.print("1 ");
 7.       try { this.wait(); } catch (Exception e) { }
 8.       System.out.print("2 ");
 9.     }
10.     else {
11.       flag = true;
12.       System.out.print("3 ");
13.       try { Thread.sleep(2000); } catch (Exception e) { }
14.       System.out.print("4 ");
15.       notify();
16.     }
17.   }
18.   public static void main(String [] args) {
19.     Waiting w = new Waiting();
20.     new Thread(w).start();
21.     new Thread(w).start();
22.   }
23. }

Which two are true? (Choose two.)


A     The code outputs 1 3 4.
B     The code outputs 3 4 1.
C     The code outputs 1 2 3 4.
D     The code outputs 1 3 4 2.
E     The code never completes.
F     The code runs to completion.


B and E are correct. Because run is synchronized, the first thread completes the entire else block before the second thread can enter run. The notify is issued before the wait, so the code hangs.

However, if line 2 sets flag to true, then the correct answers would be D and E. First thread executes in if block, sets flag to true and prints 1. It then waits while the Second thread execute. Since Second thread's copy is false, it goes into the else block, prints 3, then sleeps for 2 seconds before printing 4 and notifying the First thread that it has finished executing. First thread will then print 2. Code runs to completion.

No comments:

Post a Comment