首先實現一個死鎖程序。
public class DeadLockSample extends Thread {
private String first;
private String second;
public DeadLockSample(String name, String first, String second) {
super(name);
this.first = first;
this.second = second;
}
@Override
public void run() {
synchronized (first) {
System.out.println(this.getName() + " obtained: " + first);
try {
Thread.sleep(3000L);
synchronized (second) {
System.out.println(this.getName() + " obtained: " + second);
}
} catch (InterruptedException e) {
// do nothing
}
}
}
public static void main(String[] args) throws InterruptedException {
/**
ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();
Runnable dlCheck = new Runnable() {
@Override
public void run() {
long[] threadIds = mxBean.findDeadlockedThreads();
if (threadIds != null) {
ThreadInfo[] threadInfos = mxBean.getThreadInfo(threadIds);
System.out.println("Detected deadlock threads:");
for (ThreadInfo threadInfo : threadInfos) {
System.out.println(threadInfo.getThreadName());
}
}
}
};
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
scheduledExecutorService.scheduleAtFixedRate(dlCheck, 5L, 10L, TimeUnit.SECONDS);
*/
String lockA = "lockA";
String lockB = "lockB";
DeadLockSample t1 = new DeadLockSample("Thread1", lockA, lockB);
DeadLockSample t2 = new DeadLockSample("Thread2", lockB, lockA);
t1.start();
t2.start();
t1.join();
t2.join();
}
}
運行程序
分析
通過jps命令或者ps命令確定運行的進程ID
然後使用jstack命令獲取線程棧信息。
jstack 98485
可以看看這裏頭是否有BLOCKED狀態的線程,這樣很快就能定位出來。
我們需要區分線程狀態->查看等待目標->對比持有Monitor等持有的狀態。