Threading Model   «Prev 


Thread Invokes synchronized Method and the Synchronization Process

Consider the following code:
public class Test extends Thread{
 static Object obj = new Object();
 static int x, y;
 public void run(){
  synchronized(obj){
   for(;;){
    x++; y++; System.out.println(x+" "+y);
   }
  }
 }
 public static void main(String[] args){
  new Test().start();
  new Test().start();
 }
}

What will the above code print?
  1. It will keep on printing same values for x and y incrementing by 1 on each line.
  2. It will keep on printing same values for x and y but they may be incrementing by more than 1 on each line.
  3. It may print different values for x and y but both the values will be incrementing by 1 on each line.
  4. You cannot say anything about the values.


Answer: a
Explanation:
There are two threads created by the main method. However, when one of the threads enters the run() method, it acquires the lock on obj and enters into an infinite loop. Now, the second thread also enters run but has to wait to acquire the same lock since obj is a static field. So, in effect, only the thread that gets the lock first, keeps on running. The second thread never gets a chance. Therefore,
  1. the printed values are sequential,
  2. x and y are always printed as equal and
  3. they get incremented by 1 on each line.