Learnitweb

Write a Java program to demonstrate deadlock

Deadlock is a situation when two or more threads are indefinitely blocked waiting for each other.

In below example, there are two threads, Thread1 and Thread2. Two resources are represented by two strings, resource1 and resource2. Thread1 first gets a lock on resource1 and then resource2. Thread2 first gets a lock on resource2 and then resource1. When both threads are started, any of the two threads may get a chance to execute first and it will get a lock on one resource and will try to get lock on another resource. But the other resource will already be locked by the second thread. Thus two threads will be in a deadlock situation.

public class DeadlockExample {  
  public static void main(String[] args) {  
    final String resource1 = "This is first resource";  
    final String resource2 = "This is second resource";  
    
    /*
     * Thread1 here gets a lock on resource1 then resource 2
     */
    Thread t1 = new Thread() {  
      public void run() {  
          synchronized (resource1) {  
        	  System.out.println("Thread 1: lock on resource 1");  
        	  
        	  try {
				Thread.sleep(2000);
        	  } catch (InterruptedException e) {
				e.printStackTrace();
        	  }
           
           synchronized (resource2) {  
        	   System.out.println("Thread 1: lock on resource 2");  
           }  
         }  
      }  
    };  
  
    /*
     * Thread2 here gets a lock on resource2 first then on resource1  
     */
    Thread t2 = new Thread() {  
      public void run() {  
        synchronized (resource2) {  
          System.out.println("Thread 2: lock on resource 2");  
  
          try { 
        	  	Thread.sleep(2000);
          } catch (Exception e) {}  
  
          synchronized (resource1) {  
            System.out.println("Thread 2: lock on resource 1");  
          }  
        }  
      }  
    };  
    t1.start();  
    t2.start();  
  }  
}  

Output

Thread 1: lock on resource 1
Thread 2: lock on resource 2