我在玩线程,从我的程序中发现了一些我无法理解的奇怪输出。 这是我的 Self 类:
pip install --upgrade scikit-learn
这是我从 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” 永远不会被打印?为什么“Back from where ever I was”总是出现在与线程 t 相关的任何消息之后?
答案 0 :(得分:10)
消息"Message 3"
未显示,因为主线程的“中断状态”已被调用 Thread.interrupted()
清除。这是实例方法 isInterrupted
和静态方法 interrupted
之间的主要区别。前者不清除“中断状态”。
查看 javadoc 了解更多详情。 https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#interrupted()