I have a sample example to show the deadlock situation which may give a
clear idea
<code>
/**
* Thread-1 acquires a lock on lock1 but needs lock2.
* Thread-2 has acquired a lock on lock2 and needs to acquire lock1. Neither thread will
* yield and neither will progress. This is deadlock. Figure 4-7 shows the output.
* the output is:
* Thread-1:locked 2, trying to get lock1
* Thread-0:locked 1, trying to get lock2
*/
public class DeadLockExample {
public static void main(
String args[]){
DeadLockExample dle = new DeadLockExample();
Object lock1 = new Object();
Object lock2 = new Object();
Runner1 thread1 = dle.new Runner1();
Runner2 thread2 = dle.new Runner2();
thread1.lock1 = lock1;
thread2.lock1 = lock1;
thread1.lock2 = lock2;
thread2.lock2 = lock2;
thread1.start();
thread2.start();
}
/**
* Lock object 1 then wait for object 2.
*/
class Runner1 extends Thread{
public Object lock1;
public Object lock2;
public void run(){
synchronized(lock1){
delay();
String msg = ":locked 1, trying to get lock2";
System.out.println(Thread.currentThread().getName()+ msg);
synchronized(lock2) {
System.out.println("locked 2");
}
}
}
}
/**
* Lock object 2 then wait for object 1.
*/
class Runner2 extends Thread{
public Object lock1;
public Object lock2;
public void run(){
synchronized(lock2){
delay();
String msg =":locked 2, trying to get lock1";
System.out.println(Thread.currentThread().getName() + msg);
synchronized(lock1){
System.out.println("locked 1");
}
}
}
}
/**
* build in a delay
*/
private static void delay(){
try{
String msg = Thread.currentThread().getName() + "
elay";
Thread.currentThread().sleep((long)(Math.random()*1000));
}catch(InterruptedException ie){
ie.printStackTrace();
}
}
}
</code>
I hope this may help