Interview Questions

Output question 10.

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

70. Output question 10.

class MyRunnable implements Runnable{
public void run(){
method();
}
synchronized void method(){
for(int i=0;i<2;i++){
System.out.println(Thread.currentThread().getName());
}
}
}
public class MyClass {
public static void main(String...args){
MyRunnable runnable=new MyRunnable();
Thread thread1=new Thread(runnable,"Thread-1");
Thread thread2=new Thread(runnable,"Thread-2");
thread1.start();
thread2.start();
}
}
//q6


Answer.
Deadlock is formed in above program :
Thread-1 acquires lock on String.class and then calls sleep() method which gives Thread-2 the chance to execute immediately after Thread-1 has acquired lock on String.class and Thread-2 acquires lock on Object.class then calls sleep() method and now it waits for Thread-1 to release lock on String.class. Conclusion:
Now, Thread-1 is waiting for Thread-2 to release lock on Object.class and Thread-2 is waiting for Thread-1 to release lock on String.class and deadlock is formed.

/*OUTPUT
4
1
*/

(Continued on next question...)

Other Interview Questions