2018-08-02 IntelliJ IDEA - Debug
2018-08-02 本文已影响267人
Albert陈凯
https://blog.csdn.net/nextyu/article/details/79039566
IntelliJ IDEA - Debug 调试多线程程序
新建 MyRunnable
public class MyRunnable implements Runnable {
@Override
public void run() {
Thread currentThread = Thread.currentThread();
System.out.println(currentThread.getName() + "-------------进入");
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(currentThread.getName() + "-------------离开");
}
}
}
创建三个线程
public class MyTest {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread1 = new Thread(myRunnable, "线程1");
Thread thread2 = new Thread(myRunnable, "线程2");
Thread thread3 = new Thread(myRunnable, "线程3");
thread1.start();
thread2.start();
thread3.start();
}
}
打断点

Debug 运行 MyTest.main()
下文默认线程的执行顺序为:线程1->线程2->线程3。(实际情况不一定如此)

你会发现 idea 会停在断点处,上面显示当前线程为“线程1”(注意,这里可能为“线程2”或者“线程3”,因为不确定哪个线程先抢到资源)。
然后继续运行程序 F9,跳到下一个断点

你会发现控制台三个线程的日志都打印出来了
线程1-------------进入
线程2-------------进入
线程3-------------进入
也就是说,idea 只停留在了“线程1”的断点上,“线程2”和“线程3”的断点直接忽略了。
这不是我们想要的,我们希望每个线程的断点都会停留。可以做如下设置。
设置
断点上直接右键设置
把 All 改为 Thread。如果点了 Make Default ,那么后续加上的断点都是 Thead 设置,之前加上的断点不影响。

把上面的两个断点都改为 Thread 设置,再 Debug 运行 MyTest.main()。
你会发现 idea 首先留在了“线程1”的断点上,F9,继续运行,接着会停留在 “线程2”的断点上,F9,继续运行,又会停留在 “线程3”的断点上。
或者打开断点视图设置
和上面的效果是一样的。

结语
由于本人知识和能力有限,文中如有没说清楚的地方,希望大家能在评论区指出,以帮助我将博文写得更好。
</article>
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nextyu/article/details/79039566