Deadlocks are caused by threads waiting for each other
/**
* Deadlock Case
*/
public class TestDeadLock {
public void run() {
MyThread mt = new MyThread();
new Thread(mt, "Zhang San").start();
new Thread(mt, "Li Si").start();
}
class MyThread implements Runnable {
private final Object o1 = new Object();
private final Object o2 = new Object();
private boolean flag = true;
@Override
public void run() {
if (flag) {
flag = false;
synchronized (o1) {
System.out.println(Thread.currentThread().getName() + " have o1");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o2) {
System.out.println(Thread.currentThread().getName() + " have o2");
}
}
} else {
flag = true;
synchronized (o2) {
System.out.println(Thread.currentThread().getName() + " have o2");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (o1) {
System.out.println(Thread.currentThread().getName() + " have o1");
}
}
}
}
}
public static void main(String[] args) {
new TestDeadLock().run();
}
}
explain
- When a thread 1 enters the running state first, flag = true, obtains the o1 object, and then sleeps (without releasing the lock)
- At this time, when another thread 2 enters the running state, flag = true. Since thread 1 is in sleep and state, and has not yet acquired the o2 object, thread 2 can acquire the o2 object at this time. Then go to sleep (do not release lock)
- Now both threads have finished sleeping. If we get the resources owned by each other and wait for each other, there will be a deadlock.