-
Notifications
You must be signed in to change notification settings - Fork 122
/
DeadLockSampleV2.java
70 lines (60 loc) · 2.31 KB
/
DeadLockSampleV2.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package deadLock;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class DeadLockSampleV2 extends Thread {
private final String first;
private final String second;
public DeadLockSampleV2(String name, String first, String second) {
super(name);
this.first = first;
this.second = second;
}
public void run() {
synchronized (first) {
System.out.println(this.getName() + this.getId() + " obtained: " + first);
try {
Thread.sleep(1000L);
synchronized (second) {
System.out.println(this.getName() + " obtained: " + second);
}
} catch (InterruptedException e) {
// Do nothing
}
}
}
public static void main(String[] args) throws InterruptedException {
long pid = ProcessHandle.current().pid();
System.out.println("pid:" + pid);
ThreadMXBean mbean = ManagementFactory.getThreadMXBean();
// 死锁检测
Runnable dlCheck = new Runnable() {
@Override
public void run() {
long[] threadIds = mbean.findDeadlockedThreads();
if (threadIds != null) {
ThreadInfo[] threadInfos = mbean.getThreadInfo(threadIds);
System.out.println("Detected deadlock threads:");
for (ThreadInfo threadInfo : threadInfos) {
System.out.println(threadInfo.getThreadName());
}
}
}
};
// 稍等5秒,然后每10秒进行一次死锁扫描
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(dlCheck, 5L, 10L, TimeUnit.SECONDS);
// 死锁样例代码
String lockA = "lockA";
String lockB = "lockB";
DeadLockSampleV2 t1 = new DeadLockSampleV2("Thread1", lockA, lockB);
DeadLockSampleV2 t2 = new DeadLockSampleV2("Thread2", lockB, lockA);
t1.start();
t2.start();
t1.join();
t2.join();
}
}