Deadlock in Java
Dead lock can happen when two threads tries to lock on Object which is already locked by each other thread. In general terms lets say t1 and t2 threads acquired a locks on lock1 and lock2 respectively.
Now t1 thread trying to lock on lock2 and t2 thread trying to acquire lock on lock1, this leads to a dead lock or this situation can be called as dead lock situation.
Deadlock example
public class DeadLockExample { public static void main(String[] args) { String lock1=new String("Lock1"); String lock2=new String("Lock2"); Thread1 t1=new Thread1(lock1,lock2); Thread2 t2=new Thread2(lock1,lock2); t1.start(); t2.start(); } } class Thread1 extends Thread { public String lock1; public String lock2; Thread1(String lock1,String lock2) { this.lock1=lock1; this.lock2=lock2; } public void run() { synchronized (this.lock1) { try { Thread.sleep(10000); //kept Sleeping so that next thread can start and comes to running } catch (InterruptedException e) { e.printStackTrace(); } synchronized (this.lock2) { System.out.println(this.lock2); } } } } class Thread2 extends Thread { public String lock1; public String lock2; public Thread2(String lock1, String lock2) { this.lock1 = lock1; this.lock2 = lock2; } public void run() { synchronized (this.lock2) { try { Thread.sleep(10000); //kept Sleeping so that next thread can start and comes to running } catch (InterruptedException e) { e.printStackTrace(); } synchronized (this.lock1) { System.out.println(this.lock1); } } } }
The above example will lead to a dead lock situation, to check the dead lock you may need to trigger the thread dump for the above program.
To Exit from the above program just stop the execution forcefully by killing or in other words.