Saturday, August 14, 2010

Multithreading: Lockdown.java

Courtesy of education.oracle.com

Given: 

5. public class Lockdown implements Runnable {
6.   public static void main(String[] args) {
7.     new Thread(new Lockdown())start();
8.     new Thread(new Lockdown())start();
9.   }
10.   public void run() { locked(Thread.currentThread()getId()); }
11.   synchronized void locked(long id) {
12.     System.out.print(id + "a ");
13.     System.out.print(id + "b ");
14.   }
15. }


What is true about possible sets of output from this code?
a) Set 6a 7a 7b 8a and set 7a 7b 8a 8b are both possible.
b) Set 7a 7b 8a 8b and set 6a 7a 6b 7b are both possible. (*)
c) It could be set 7a 7b 8a 8b but set 6a 7a 6b 7b is NOT possible.
d) It could be set 7a 8a 7b 8b but set 6a 6b 7a 7b is NOT possible.

b is correct. Two different Lockdown objects are using the locked() method. However if locked() was a static method, then it belongs to the class, and it is essenntial the one and only "instance", hence the two threads would be competing for who gets into locked().

No comments:

Post a Comment