

Now Thread thread2 starts its execution and synchronizes on the object reference obj2.

Thread thread1 then goes to sleep by calling sleep() method and allows Thread thread2 to start its execution.Ģ. First, Thread thread1 starts its execution and synchronizes on the object obj1 that prevents another thread to call method display1 on obj1 reference variable.

Thread2 waiting for thread1 to release lockġ. Thread1 waiting for thread2 to release lock ("Thread2 waiting for thread1 to release lock") ("Thread1 waiting for thread2 to release lock") Let’s take an example program to demonstrate deadlock. We should take care to avoid deadlock while coding. Therefore, thread deadlock is a drawback in a program. When thread deadlock occurs in a program, the further execution of program will stop. In this case, none of the threads will unlock the lock because of not completing their execution process. During execution, thread t1 is waiting for data that is locked by thread t2 and t2 is waiting for data that is locked by thread t1. Both threads are running concurrently (simultaneously). Similarly, assume that there are two threads t1 and t2. This situation is called deadlock in Java. Thus, none of the friends will release stationary objects and both will wait infinitely for each other to release stationary. Later on, Jerry needs an eraser but John will not give it as his drawing is not completed because of waiting for the ruler. But Jerry will not give it because he is using it currently. Now John needs a ruler to continue his drawing. Currently, eraser and ruler are not occupied by any of the friends. Meanwhile, Jerry needs ruler, so he will use (lock) the ruler. During drawing, John needs an eraser, so he will use (lock) the eraser. Realtime Example of Deadlock in JavaĪ simple real-time example of deadlock is that suppose there are two friends John and Jerry that are drawing a diagram. Let’s understand the concepts of deadlock with realtime examples. Since both threads are waiting for each other to unlock resources R1 and R2, therefore, these mutually exclusive conditions are called deadlock in Java.
