Thread t = new Thread(){
public void run(){
while(true){
}
}
};
t.start();
t.interrupt();
System.out.println(t.interrupted());
我遇到一个问题,我在线程上调用中断,然后检查线程是否被中断 - 它总是返回 false。为什么?
最佳答案
来自Java Thread docs (我的斜体):
static boolean interrupted()
: Tests whether the current thread has been interrupted.
它实际上是一个静态方法(a),旨在在目标线程中使用,以查看是否有人中断了它,因此您可以在中使用它t.run()
本身。
如果线程碰巧调用抛出该异常的方法(例如 Thread.sleep()),则线程也可以收到 InterruptedException 通知。
并且,根据上面的链接,在 Thread.interrupted()
的详细描述中,线程清除其自身中断状态的方式是调用它:
The interrupted status of the thread is cleared by this method.
要测试不同线程是否已被中断,请使用非静态isInterrupted()
:
boolean isInterrupted()
: Tests whether this thread has been interrupted.
(a) 我经常认为,如果您在某个对象上调用静态(类级)方法,编译器会警告您,这将是一个好主意。具体对象。我见过一些人们被类似问题困扰的事件。
但后来我想,为什么呢?使用某种语言的人应该理解该语言,甚至是它的黑暗角落,C(例如)有相当多的一些这样的:-)
关于java - 中断调用后线程在中断调用时返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28711948/