程序

假设有如下一个程序

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();
    }
}
调试问题重现

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

设置断点每个线程都会走

右键断点,点选Thread
IDEA多线程调试_thread_04

设置只调试一条线程

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