Deadlock is a condition where two or more threads are waiting for a resource that is held by another thread, effectively staying in the wait
loop forever.
Let's see an example of a Java program that is in deadlock.
Note: If the program seems stuck, it is in deadlock. Wait for the execution time to complete.
public class Deadlock{public static void main(String[] args){final String s1 = "anjana";final String s2 = "shankar";Thread t1 = new Thread() {public void run(){synchronized(s1){System.out.println("Thread 1: Locked s1");try{ Thread.sleep(100);} catch(Exception e) {}synchronized(s2){System.out.println("Thread 1: Locked s2");}}}};Thread t2 = new Thread() {public void run(){synchronized(s2){System.out.println("Thread 2: Locked s2");try{ Thread.sleep(100);} catch(Exception e) {}synchronized(s1){System.out.println("Thread 2: Locked s1");}}}};t1.start();t2.start();}}
The following are some recommendations in order to avoid deadlocks, although it is not possible to guarantee deadlock avoidance.
Thread.join()
with a maximum wait time that a thread can take.