如何在暂停程序的线程之间切换?
或任何有关使用Intellij Idea进行多线程调试的教程,描述基本功能 - 暂停,恢复,在线程之间切换。
Netbeans的非常好的教程/分步指南: 例如https://netbeans.org/kb/docs/java/debug-multithreaded.html
答案 0 :(得分:15)
Trick是将断点暂停策略设置为 - Thread。
一旦完成线程将命中断点并阻塞,现在可以切换活动线程以检查竞争条件/死锁。
以下代码段用于创建死锁:
public static void main(String args[]) {
Thread thread1 = new Thread(null, new MyThread(obj1, obj2), "Thread-1");
Thread thread2 = new Thread(null, new MyThread(obj2, obj1), "Thread-2");
thread1.start();
thread2.start();
}
class MyThread implements Runnable {
private Object obj1;
private Object obj2;
MyThread(Object obj1, Object obj2) {
this.obj1 = obj1;
this.obj2 = obj2;
}
@Override
public void run() {
System.out.println("Acquiring locks");
synchronized (obj1){
System.out.println("Acquired 1st lock");
synchronized (obj2){
System.out.println("Acquired 2nd lock");
}
System.out.println("Released 2nd lock");
}
System.out.println("Released 1st lock");
}
}
答案 1 :(得分:5)