java实现死锁

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
public class DeadLockDemo {

private static Object resource1 = new Object();
private static Object resource2 = new Object();

public static void main(String[] args) {
new Thread(() -> {
synchronized (resource1) {

System.out.println(Thread.currentThread() + "get resource1");

try {
// 线程休眠,保证线程2先获得资源2
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(Thread.currentThread() + "waiting get resource2");

synchronized (resource2) {
System.out.println(Thread.currentThread() + "get resource2");
}
}
}, "T1").start();

new Thread(() -> {
synchronized (resource2) {

System.out.println(Thread.currentThread() + "get resource2");

try {
// 线程休眠,保证线程1先获得资源1
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(Thread.currentThread() + "waiting get resource1");

synchronized (resource1) {
System.out.println(Thread.currentThread() + "get resource1");
}
}
}, "T2").start();

}
}

程序结果

1
2
3
4
Thread[T1,5,main]get resource1
Thread[T2,5,main]get resource2
Thread[T1,5,main]waiting get resource2
Thread[T2,5,main]waiting get resource1

死锁原因

T1和T2各自同时占有resource1和resource2,而又分别要使用resource2和resource1,因此发生死锁。

解决方法

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
public class DeadLockDemo {

private static Object resource1 = new Object();
private static Object resource2 = new Object();

public static void main(String[] args) {
new Thread(() -> {
synchronized (resource1) {

System.out.println(Thread.currentThread() + "get resource1");

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(Thread.currentThread() + "waiting get resource2");

synchronized (resource2) {
System.out.println(Thread.currentThread() + "get resource2");
}
}
}, "T1").start();

new Thread(() -> {
synchronized (resource1) {

System.out.println(Thread.currentThread() + "get resource2");

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(Thread.currentThread() + "waiting get resource1");

synchronized (resource2) {
System.out.println(Thread.currentThread() + "get resource1");
}
}
}, "T2").start();

}
}

程序结果

1
2
3
4
5
6
Thread[T1,5,main]get resource1
Thread[T1,5,main]waiting get resource2
Thread[T1,5,main]get resource2
Thread[T2,5,main]get resource2
Thread[T2,5,main]waiting get resource1
Thread[T2,5,main]get resource1

分析

可以让两个线程按照顺序依次使用resource1和resource2