IDEA多线程调试

时间:2022-07-23
本文章向大家介绍IDEA多线程调试,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

程序

假设有如下一个程序

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();
    }
}

调试问题重现

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

可以看到调试的时候会在多线程之间乱跳,很不利于问题的排查。而且似乎线程的第一个断点没有走。如何设置断点每个线程都会走呢?

设置断点每个线程都会走

右键断点,点选Thread

在这里插入图片描述

设置只调试一条线程

右键断点,点选Thread,同时加上currentThread.getName().equals("线程1")条件。当然这个其实是有一定的问题的,因为项目里面用的线程一般是线程池,我们也很少去指定线程的名称,所以这个方法有一定的缺陷,有其他好的办法欢迎评论区指出。

在这里插入图片描述

参考:https://blog.csdn.net/nextyu/article/details/79039566