Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
104 lines (80 loc) · 2.55 KB

File metadata and controls

104 lines (80 loc) · 2.55 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package thread;
/**
* Created by yahier on 10/30/18.
* 测试 死锁
*/
public class Deadlock {
private String objID;
private Deadlock(String id) {
objID = id;
}
public static void main(String[] args) {
final Deadlock obj1 = new Deadlock("obj1");
final Deadlock obj2 = new Deadlock("obj2");
Thread threadA = new Thread(() -> {
obj1.checkOther(obj2);
}, "threadA");
threadA.start();
try {
Thread.sleep(200);
} catch (InterruptedException x) {
//pass
}
Thread threadB = new Thread(() -> {
obj2.checkOther(obj1);
}, "threadB");
threadB.start();
try {
Thread.sleep(5000);
} catch (InterruptedException x) {
//pass
}
threadPrint("finished sleeping");
threadPrint("about to interrupt() threadA");
threadA.interrupt();
try {
Thread.sleep(1000);
} catch (InterruptedException x) {
}
threadPrint("about to interrupt() threadB");
threadB.interrupt();
try {
Thread.sleep(1000);
} catch (InterruptedException x) {
}
threadPrint("did that break the deadlock?");
}
/**
* 同时进入了此方法,因为 锁的对象不同
*/
private synchronized void checkOther(Deadlock other) {
print("entering checkOther()");
try {
Thread.sleep(2000);
} catch (InterruptedException x) {
}
print("in checkOther() - about to " + "invoke 'other.action()'");
//调用other对象的action方法,由于该方法是同步方法,因此会试图获取other对象的对象锁
other.action();
print("leaving checkOther()");
}
/**
* 都不能进入到此方法。
* 在执行到上面的other.action() 时,由于两个线程都在试图获取对方的锁,但对方都没有释放自己的锁,因而便产生了死锁,在主线程中试图中断两个线程,但都无果
*/
private synchronized void action() {
print("entering action()");
try {
Thread.sleep(500);
} catch (InterruptedException x) {
}
print("leaving action()");
}
public void print(String msg) {
threadPrint("objID=" + objID + " - " + msg);
}
private static void threadPrint(String msg) {
String threadName = Thread.currentThread().getName();
System.out.println(threadName + ": " + msg);
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.