???????????????????????????????????handler??????System.err??????????????????????????У????????????????????????磺
public class DeadlockConsoleHandler implements DeadlockHandler {
@Override
public void handleDeadlock(final ThreadInfo[] deadlockedThreads) {
if (deadlockedThreads != null) {
System.err.println("Deadlock detected!");
Map<Thread?? StackTraceElement[]> stackTraceMap = Thread.getAllStackTraces();
for (ThreadInfo threadInfo : deadlockedThreads) {
if (threadInfo != null) {
for (Thread thread : Thread.getAllStackTraces().keySet()) {
if (thread.getId() == threadInfo.getThreadId()) {
System.err.println(threadInfo.toString().trim());
for (StackTraceElement ste : thread.getStackTrace()) {
System.err.println("t" + ste.toString().trim());
}
}
}
}
}
}
}
}
????????????????е???????з??????в???????????????????????????????????????????????????????????λ?ú?????????????????????——??????????????????????????????????????????????????????????????????????????????????????????????????findDeadlockedThreads??????????д????????????????????NullPointerException???????????????????????????????????????????????????????е??
DeadlockDetector deadlockDetector = new DeadlockDetector(new DeadlockConsoleHandler()?? 5?? TimeUnit.SECONDS);
deadlockDetector.start();
final Object lock1 = new Object();
final Object lock2 = new Object();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock1) {
System.out.println("Thread1 acquired lock1");
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException ignore) {
}
synchronized (lock2) {
System.out.println("Thread1 acquired lock2");
}
}
}
});
thread1.start();
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock2) {
System.out.println("Thread2 acquired lock2");
synchronized (lock1) {
System.out.println("Thread2 acquired lock1");
}
}
}
});
thread2.start();
?????????
????Thread1 acquired lock1
????Thread2 acquired lock2
????Deadlock detected!
????“Thread-1” Id=11 BLOCKED on java.lang.Object@68ab95e6 owned by “Thread-0” Id=10
????deadlock.DeadlockTester$2.run(DeadlockTester.java:42)
????java.lang.Thread.run(Thread.java:662)
????“Thread-0” Id=10 BLOCKED on java.lang.Object@58fe64b9 owned by “Thread-1” Id=11
????deadlock.DeadlockTester$1.run(DeadlockTester.java:28)
????java.lang.Thread.run(Thread.java:662)
????????????????????????????????????????????????????????????????????????ü????Ρ???????????????????????????????????????????????????????壬??????????????????????????????????????????????????????????????????η???????????????й??????????????y???????????????????????????????????????