Saturday, August 21, 2010

Multithreading: Waiter.java

Courtesy of Sun Web Learning Center


 3. class Waiter implements Runnable {
 4.   int state;
 5.   public synchronized void run() {
 6.     if (state++ < 3) {
 7.       System.out.print(" " + Thread.currentThread().getId());
 8.       try { this.wait(); } catch (Exception e) { }
 9.       System.out.print(" " + Thread.currentThread().getId());
10.     }
11.     else { notify();   notifyAll(); }
12.   }
13.   public static void main(String [] args) {
14.     Waiter w1 = new Waiter();   Waiter w2 = new Waiter();
15.     new Thread(w1).start();     new Thread(w1).start();
16.     new Thread(w2).start();     new Thread(w2).start();
17. } }


Which two are true? (Choose two.)


A     The program never completes.
B     The program runs to completion.
C     The output could be 6 7 9 8.
D     The output could be 6 7 9 6.
E     The output could be 6 7 8 6 7 10.
F     The output could be 6 7 10 7 10 6.

A and C are correct. Because there are two runnables, neither's state ever equals 3, so the else block is never executed and the threads wait forever. D is incorrect because four different threads are started and each must have a unique Id.

Another way to understand this problem is with modified code below.

Two runnable are executing eight threads each, and the state is being printed before and after the try block. Also, I removed the notify() and kept notifyAll() because notifyAll() will notify ALL the threads that are waiting to enter in the synchronized block, so notify() is really redundant.



 










Compiling and running this code will display the thread id, where the thread is located, i.e. before or after the try state, and also, the state number.

No comments:

Post a Comment