Interview Questions

Output question 8.

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

68. Output question 8.

class MyRunnable1 implements Runnable{
@Override
public void run(){

synchronized (this) {
try{
System.out.print("2 ");
Thread.sleep(1000);
}catch(InterruptedException e){e.printStackTrace();}

this.notify();

System.out.print("3 ");

}
}

}

class MyRunnable2 extends Thread{
MyRunnable1 prod;

MyRunnable2(MyRunnable1 obj){
prod=obj;
}

public void run(){
synchronized (this.prod) {

System.out.print("1 ");
try{
this.prod.wait();
}catch(InterruptedException e){e.printStackTrace();}

}

System.out.print("4 ");

}

}

public class MyClass {
public static void main(String args[]) throws InterruptedException{

MyRunnable1 myRunnable1=new MyRunnable1();
MyRunnable2 myRunnable2=new MyRunnable2(myRunnable1);

Thread thread1=new Thread(myRunnable1,"Thread-1");
Thread thread2=new Thread(myRunnable2,"Thread-2");

thread2.start();
Thread.sleep(100); //This minor delay will ensure that Thread-1 thread starts Thread-2
thread1.start();


}
}



Answer.
Wait() method causes the current thread to wait until another thread invokes the notify() or notifyAll() method for this object.
Now, as soon as notify() or notifyall() method is called it notifies the waiting thread, but object monitor is not yet available. Object monitor is available only when thread exits synchronized block or synchronized method. So, what happens is code after notify() is also executed and execution is done until we reach end of synchronized block.
The awakened threads will not be able to proceed until the current thread relinquishes the lock on this object

/*OUTPUT
1 2 3 4
*/

(Continued on next question...)

Other Interview Questions