Deadlock in multithreading is a situation where two or more than two are a lock, waiting for each other.
When the first thread needs to use the same lock or wait for the object lock which is acquired by a second thread and the second thread also waits for the lock acquired by a first thread then the deadlock occurs because they are waiting for each other which is caused by synchronized keyword.
One of the example where Deadlock occur is the Dining Philosophers problem in C.
Example: Java program for Deadlock demonstration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | public class NamesDeadLock { public static void main(String[] args) { String Lock1 = "Prashant"; String Lock2 = "Karan"; //Following, the two different thread are created t1 and t2 // here t1 tries to lock Lock1 then Lock2 Thread t1 = new Thread() { public void run() { synchronized (Lock1) { System.out.println("Thread 1: Lock1 locked"); try { Thread.sleep(100); } catch (Exception e) {} synchronized (Lock2) { System.out.println("Thread 1: Locked2 locked"); } } } }; // here t2 tries to lock Lock2 then Lock1 Thread t2 = new Thread() { public void run() { synchronized (Lock2) { System.out.println("Thread 2: Lock2 locked"); try { Thread.sleep(100); } catch (Exception e) {} synchronized (Lock1) { System.out.println("Thread 2: Lock1 locked"); } } } }; t1.start(); t2.start(); } } |
Output of Deadlock:
1 2 | Thread 1: Lock1 locked Thread 2: Lock2 locked |