Java 如何在 IntelliJ 中调试多线程应用程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27784413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:02:14  来源:igfitidea点击:

How to debug a multi-threaded app in IntelliJ?

javamultithreadingdebuggingintellij-idea

提问by m0skit0

I'm having a strange issue with multiple threads and breakpoints in IntelliJ IDEA 14.0.2. Code after the breakpoint is executed before it stops on it.

我在 IntelliJ IDEA 14.0.2 中遇到了多线程和断点的奇怪问题。断点之后的代码在它停止之前执行。

import java.util.concurrent.atomic.AtomicInteger;


public class Main {

    private static final int NUM_CLIENTS = 1000;

    static class TestRunnable implements Runnable {
        AtomicInteger lock;
        @Override
        public void run() {
            synchronized (this.lock) {
                int curCounter = this.lock.addAndGet(1);
                System.out.println("Thread: " + Thread.currentThread().getName() + "; Count: " + curCounter);
                if (curCounter >= NUM_CLIENTS) {
                    lock.notifyAll();
                }
            }
        }
    }

    public static void main(final String args[]) {
        final AtomicInteger lock = new AtomicInteger(0);
        for (int i = 0; i < NUM_CLIENTS; i++) {
            TestRunnable tr1 = new TestRunnable();
            tr1.lock = lock;
            new Thread(tr1).start();
        }
        synchronized (lock) {
            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Main woken up");
        }
    }
}

When I put a breakpoint (Suspend All) at line 12, synchronized (this.lock), System.out.printlnstill executes (sometimes several times). Here's a screenshot:

当我在第 12 行放置断点 (Suspend All) 时synchronized (this.lock)System.out.println仍然会执行(有时会执行几次)。这是一个屏幕截图:

enter image description here

在此处输入图片说明

As far as I know, all threads should stop at the breakpoint.

据我所知,所有线程都应该在断点处停止。

采纳答案by Makoto

The documentation reads confusingly, but this is the relevant block.What it distills down to is setting the property to suspend on threads, and not the entire application instead. This will cause you to hit the break point on each individual thread instead of an arbitrary, indeterminate thread.

该文档读起来令人困惑,但这是相关的块。它的精髓是将属性设置为在线程上挂起,而不是整个应用程序。这将导致您在每个单独的线程而不是任意的、不确定的线程上遇到断点。

Suspend box checked with Thread radio button selected.

选中“线程”单选按钮并选中“暂停”框。

  • Suspend Policy: All
    • When a breakpoint is hit, all threads are suspended.
  • Suspend Policy: Thread
    • When the breakpoint is hit, the thread where the breakpoint is hit is suspended.
  • 暂停政策:全部
    • 当遇到断点时,所有线程都将挂起。
  • 暂停策略:线程
    • 当断点被击中时,被击中断点的线程被挂起。