Think about two threads Th1 and Th2, each of which has locked or taken up a resource (Re1 or Re2, respectively). Currently, thread Th1 is asking for resource Re2, and thread Th2 is asking for resource Re1. Till the thread execution is complete, neither of the threads Th1 nor Th2 will release their respective resources Re1 and Re2.
DeadLock Situation
Therefore, the situation is impasse. It is a situation in which all processes are at a standstill and are actively preventing one another from continuing with execution. For an infinite amount of time, the processes in the deadlock wait for one another to release resources.
public class Main { final static String re1 = "Ankita"; final static String re2 = "Alok"; public static void main(String[] args) { // creating thread T1 Thread th1 = new Thread() { public void run() { synchronized (re1) { System.out.println("Thread Th1 locked --> Resource Re1"); try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } synchronized (re2) { System.out.println("Thread Th1 locked --> Resource Re2"); } } } }; // creating thread T2 Thread th2 = new Thread() { public void run() { synchronized (re2) { System.out.println("Thread Th2 locked --> Resource Re2"); try { Thread.sleep(100); }catch (Exception e) { e.printStackTrace(); } synchronized (re1) { System.out.println("Thread Th2 locked --> Resource Re1"); } } } }; th1.start(); th2.start(); } }
Output:
Thread Th2 locked --> Resource Re2
Thread Th1 locked --> Resource Re1
public class Main { public static void main(String ar[]) { Main test = new Main(); final Resource1 re1 = test.new Resource1(); final Resource2 re2 = test.new Resource2(); Runnable runnable1 = new Runnable() { public void run() { synchronized (re2) { try { // here we use sleep method so that both threads can start trying to lock resources Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } // Thread 1 has resource 1, but also requires resource 2. synchronized (re1) { System.out.println("Inside synchronized block 1"); } } } }; Runnable runnable2 = new Runnable() { public void run() { synchronized (re2) { // Thread 2 has resource 2, but also requires resource 1. synchronized (re1) { System.out.println("Inside synchronized block 2"); } } } }; new Thread(runnable1).start(); new Thread(runnable2).start(); } private class Resource1 { private int b = 25; public int getB() { return b; } public void setB(int b) { this.b = b; } } private class Resource2 { private int a = 10; public int getA() { return a; } public void setA(int a) { this.a = a; } } }
Output:
Inside synchronized block 1
Inside synchronized block 2
Police Colony
Patna, Bihar
India
Email:
Post your comment