死锁

死锁

两个或者多个线程互相持有对方所需要的资源,导致这些线程处于等待状态,无法前往执行

例子

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
public class DeadLock {

public static void main(String[] args) {
dead_lock();
}

private static void dead_lock() {
// 两个资源
final Object resource1 = "resource1";
final Object resource2 = "resource2";
// 第一个线程,想先占有resource1,再尝试着占有resource2
Thread t1 = new Thread() {
public void run() {
// 尝试占有resource1
synchronized (resource1) {
// 成功占有resource1
System.out.println("Thread1 1:locked resource1");
// 休眠一段时间
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 尝试占有resource2,如果不能占有,该线程会一直等到
synchronized (resource2) {
System.out.println("Thread1 1:locked resource2");
}
}
}
};
// 第二个线程,想先占有resource2,再占有resource1
Thread t2 = new Thread() {
public void run() {
// 尝试占有resource2
synchronized (resource2) {
// 成功占有resource2
System.out.println("Thread2 1 :locked resource2");
// 休眠一段时间
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 尝试占有resource1,如果不能占有,该线程会一直等到
synchronized (resource1) {
System.out.println("Thread2 2:locked resource1");
}
}
}
};
// 启动线程
t1.start();
t2.start();

try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread1 state:"+t1.getState());
System.out.println("Thread2 state:"+t2.getState());
}
}

输出结果

1
2
3
4
Thread1 1:locked resource1
Thread2 1 :locked resource2
Thread1 state:BLOCKED
Thread2 state:BLOCKED