IntelliJ IDEA Tutorial Twelve - Debug Debugging Multithreaded Programs

New 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() + "-------------离开");
        }

    }
}

Create three threads

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

break point

Debug run MyTest.main()

The default thread execution order below is: thread 1 -> thread 2 -> thread 3. (Not necessarily the case in reality)

You will find that the idea will stop at the breakpoint, which shows that the current thread is "thread 1" (note that it may be "thread 2" or "thread 3" here, because it is not sure which thread grabs the resource first).

Then continue to run the program F9, jump to the next breakpoint

You will find that the logs of the three threads of the console are printed out

线程1-------------进入
线程2-------------进入
线程3-------------进入

That is to say, the idea only stays on the breakpoint of "thread 1", and the breakpoints of "thread 2" and "thread 3" are directly ignored.

This is not what we want, we want each thread's breakpoint to stick. The following settings can be made.

set up

Right-click directly on the breakpoint to set

Change All to Thread. If you click Make Default, then the breakpoints added later are the Thead settings, and the breakpoints added before will not be affected.

Change the above two breakpoints to Thread settings, and then Debug and run MyTest.main().

You will find that idea first stays on the breakpoint of "thread 1", F9, continues to run, then it will stay on the breakpoint of "thread 2", F9, continues to run, and will stay on the break of "thread 3" again Point.

Or open the breakpoint view settings

The effect is the same as above.

Epilogue

Due to my limited knowledge and ability, if there is something unclear in the text, I hope you can point it out in the comment area to help me write the blog post better.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325457784&siteId=291194637