This section provides a tutorial example on how to demonstrate a deadlock condition with two Java threads.
Deadlock: A state of execution when 2 or more threads are all put on hold,
because each of them is holding a synchronization lock while waiting for another
lock. The lock each thread is waiting for is held by one of the other threads.
So none of threads can move forward.
By definition, deadlock can only happen when the program is running multiple threads,
and multiple locks are being used by multiple threads. Therefore:
A single-threaded program will never have deadlocks.
A program with one lock will never have deadlocks.
Here is a simple program to demonstrate a deadlock with two threads and two
locks:
/**
* SimpleDeadLock.java
* Copyright (c) 2002 by Dr. Herong Yang
*/
import java.util.*;
public class SimpleDeadLock extends Thread {
public static Object l1 = new Object();
public static Object l2 = new Object();
private int index;
public static void main(String[] a) {
Thread t1 = new Thread1();
Thread t2 = new Thread2();
t1.start();
t2.start();
}
private static class Thread1 extends Thread {
public void run() {
synchronized (l1) {
System.out.println("Thread 1: Holding lock 1...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 1: Waiting for lock 2...");
synchronized (l2) {
System.out.println("Thread 2: Holding lock 1 & 2...");
}
}
}
}
private static class Thread2 extends Thread {
public void run() {
synchronized (l2) {
System.out.println("Thread 2: Holding lock 2...");
try { Thread.sleep(10); }
catch (InterruptedException e) {}
System.out.println("Thread 2: Waiting for lock 1...");
synchronized (l1) {
System.out.println("Thread 2: Holding lock 2 & 1...");
}
}
}
}
}
As the output shows, after gaining lock 1, thread 1 was put on hold to
wait for lock 2, which was held by thread 2 and it will never be release,
because thread 2 was also put on hold to wait lock 1, which was held by
thread1. So none of them could move forward. You have to press Ctrl-C
to stop program.