isInterrupted() 没有被触发

Ion*_*Kat 3 java multithreading java-8

尝试使用interrupt(),发现isInterrupted() 始终为false。

另一件事是用Thread.interrupted()替换isInterrupted()将使线程停止。

有人可以解释为什么会发生这种行为吗?

public static void main(String[] args) {
        Thread counter = new Thread(new Worker());
        counter.start();
        counter.interrupt();
    }

    static class Worker extends Thread {

        @Override
        public void run() {
            String msg = "It was interrupted"; 

            while (true) {
                if (isInterrupted()) {
                    System.out.println(msg);
                    return;
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*oni 6

你有两个线程对象:Worker它自己是一个线程,你将它包装在一个新的单独Thread对象中:

Thread counter = new Thread(new Worker());
Run Code Online (Sandbox Code Playgroud)

这两个线程对象有两个中断标志。调用counter.interrupt()在外层线程对象中设置中断标志,而调用则isInterrupted()检查内部“Worker”线程对象中的中断标志。

Thread.interrupted()使线程停止的原因是因为它检查当前正在运行的线程的中断标志,在这种情况下将是外部对象。

如果你摆脱了外部线程对象并编写了以下代码,代码会更清晰:

Worker counter = new Worker();
counter.start();
counter.interrupt();
Run Code Online (Sandbox Code Playgroud)