死锁知识点

什么是死锁

两个线程分别是线程1和线程2。线程1执行过程中,先获得对象a的锁,然后要再获得b的锁才能继续执行代码;而线程2正巧相反,先获得对象b的锁,然后要再获得a的锁才能继续执行代码。这时,两个线程都等着对方解锁,才能继续执行,这时,两个线程就进入等待状态,最终不会有线程执行。这就变成了死锁。

简单的死锁代码

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
public class DeadLockTest implements Algorithm {
public Object object1 = new Object();
public Object object2 = new Object();

@Override
public void execut() {
new Thread(new Runnable() {
@Override
public void run() {
Utils.printString("=====>>thread 1 running");
Lock1.test();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
Utils.printString("=====>>thread 2 running");
Lock2.test();
}
}).start();
}

public static class Lock1 {
public static synchronized void test(){
try {
Utils.printString(Thread.currentThread().getName() + " get lock1");
Thread.sleep(500);
Utils.printString(Thread.currentThread().getName() + " try to get lock2");
Lock2.test();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static class Lock2 {
public static synchronized void test(){
try {
Utils.printString(Thread.currentThread().getName() + " get lock2");
Thread.sleep(1000);
Utils.printString(Thread.currentThread().getName() + " try to get lock1");
Lock1.test();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

运行结果

1
2
3
4
5
6
=====>>thread 1 running
=====>>thread 2 running
Thread-0 get lock1
Thread-1 get lock2
Thread-0 try to get lock2
Thread-1 try to get lock1