JavaThreadsisInterrupted(),为什么没有出现这个输出

我正在玩线程,并从我的程序中发现了一些我无法理解的奇怪输出。这是我的 Self 类:

public class Self {

    public static void main(String[] args) {
        System.out.println("Hello from main");
       
        Thread t = Thread.currentThread();
       
        if (Thread.interrupted()) {
            System.out.println("Message 0A");
        } else {
            System.out.println("Message 0B");
        }
       
        t.interrupt();
       
        if (t.isInterrupted()) {
            System.out.println("Message 1A");
        } else {
            System.out.println("Message 1B");
        }
       
        if (Thread.interrupted()) {
            System.out.println("Message 2A");
        } else {
            System.out.println("Message 2B");
        }
       
        if (t.isInterrupted()) {
            System.out.println("Message 3");
        }
       
        System.out.println("Back from where ever I was");
    }
}

这是我从 Self 类的输出:

public class Self {

    public static void main(String[] args) {
        System.out.println("Hello from main");
       
        Thread t = Thread.currentThread();
       
        if (Thread.interrupted()) {
            System.out.println("Message 0A");
        } else {
            System.out.println("Message 0B");
        }
       
        t.interrupt();
       
        if (t.isInterrupted()) {
            System.out.println("Message 1A");
        } else {
            System.out.println("Message 1B");
        }
       
        if (Thread.interrupted()) {
            System.out.println("Message 2A");
        } else {
            System.out.println("Message 2B");
        }
       
        if (t.isInterrupted()) {
            System.out.println("Message 3");
        }
       
        System.out.println("Back from where ever I was");
    }
}

为什么“消息 3”永远不会被打印?为什么在任何与线程 t 相关的消息之后总是出现“从我所在的地方回来”

回答

该消息 "Message 3"
未显示,因为主线程的“中断状态”已被调用清除Thread.interrupted()。这是实例方法isInterrupted和静态方法之间的主要区别interrupted。前者不清除“中断状态”。

查看 javadoc 以获取更多详细信息。
https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#interrupted()


以上是JavaThreadsisInterrupted(),为什么没有出现这个输出的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>