首页 > 解决方案 > Thread.interrupted() 返回的值不正确 - 为什么?

问题描述

如果您执行以下代码,您将看到线程 is interrupted,但是,Thread.interrupted()将返回false

public class Test {

    public static void main(String args[]) {
        Thread t = new Thread() {
            public void run() {
                try {
                    synchronized (this) {
                        wait();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(Thread.interrupted());
                }
            }
        };
        t.start();

        t.interrupt();
        for (;;) {
        }

    }
}

请帮助我理解为什么会这样false,而应该是true

标签: javamultithreading

解决方案


JavaDocs是一个很棒的东西......

抛出:
InterruptedException - 如果任何线程在当前线程等待之前或期间中断了当前线程。抛出该异常时清除当前线程的中断状态。


推荐阅读