如何找到我的线程在哪里中断?

Tom*_*ica 1 java multithreading netbeans

我可能无意中更改了项目中的某些内容。现在,关键线程在不应该中断时被中断,并isInterrupted在线程应该运行时返回 true。

因为没有人会为我找到问题,所以我正在寻求帮助以找到找到它的方法。我需要找到:

  • 充其量,线程实际中断的位置并在程序运行时将其输出到控制台
  • 或者代码中所有被打断的地方,一一注释掉

因为 IDE 工具和调试器可能会在我的搜索中发挥作用,所以我将补充说我使用的是 NetBeans IDE。

Old*_*eon 5

您可以在一个特殊线程下运行它,该线程在中断时记录堆栈:

// A simple process.
class Process implements Runnable {

    @Override
    public void run() {
        try {
            while (true) {
                Thread.sleep(1000L);
            }
        } catch (InterruptedException ex) {
            System.out.println("Interrupted");
        }
    }

}

public void test() throws InterruptedException {
    Thread t = new Thread(new Process()) {
        @Override
        public void interrupt() {
            // Log a stack trace when iterrupted.
            new Exception("Where the hell did that come from!").printStackTrace(System.out);
            // Pass it up the chain.
            super.interrupt();
        }
    };
    t.start();
    Thread.sleep(2048);
    t.interrupt();
    t.join();
}
Run Code Online (Sandbox Code Playgroud)