Deadlock simulation program in Java

Here is a program in java that simulates a deadlock scenario.

 

This program creates 2 resources, resource 1 and resource 2 and creates 2 threads t1 and t2.

 

Thread t1 locks resource 1 and tries to access resource 2.
Thread t2 locks resource 2 and tries to access resource 1.

 

synchronized block provides lock on the resources so that only one thread access a resource at a time.

 

 

package com.javatutorial;

public class DeadlockSimulation extends Thread{
  
  private static String resource1 = "resource1";
  private static String resource2 = "resource2";
  
  private static class Thread1 extends Thread{
    public void run(){
      synchronized(resource1){
        System.out.println("resource 1 locked by thread 1");
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        synchronized(resource2){
          System.out.println("resource 2 is locked by thread 1");
        }
      }
    }
  }
  
  private static class Thread2 extends Thread{
    public void run(){
      synchronized(resource2){
        System.out.println("resource 2 locked by thread 2");
        try {
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        synchronized(resource1){
          System.out.println("resource 1 is locked by thread 2");
        }
      }
    }
  }
  
  public static void main(String[] args) {
    Thread1 t1 = new Thread1();
    Thread2 t2 = new Thread2();
    t1.start();
    t2.start();
    
    
  }

}

If you run this program, you will notice deadlock because the threads are waiting on each other.

© 2015, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags