为什么interrupt()没有按预期工作,它是如何工作的 [英] why interrupt() not work as expected and how does it work
问题描述
我想中断一个线程,但是调用interrupt()似乎不起作用,下面是示例代码:
I want to interrupt a thread, but invoke interrupt() seems not work, below is the sample code:
public class BasicThreadrRunner {
public static void main(String[] args) {
Thread t1 = new Thread(new Basic(), "thread1");
t1.start();
Thread t3 = new Thread(new Basic(), "thread3");
Thread t4 = new Thread(new Basic(), "thread4");
t3.start();
t1.interrupt();
t4.start();
}
}
class Basic implements Runnable{
public void run(){
while(true) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.err.println("thread: " + Thread.currentThread().getName());
//e.printStackTrace();
}
}
}
}
但是输出看起来像thead1仍然在运行。所以任何人都可以解释一下,interrupt()如何工作,谢谢
but the output looks like thead1 is still running. So could anyone explain it, how interrupt() works, thanks
推荐答案
线程仍在运行只是因为你抓住了 InterruptedException
并继续运行。 interrupt()
主要在 Thread
对象中设置一个标志,您可以使用 isInterrupted进行检查()
。它还会导致一些方法 - sleep()
, join
Object.wait()
,特别是 - 通过抛出 InterruptedException
立即返回。它还会导致某些I / O操作立即终止。如果您从 catch
块中看到打印输出,那么您可以看到 interrupt()
正在运行。
The thread is still running simply because you catch InterruptedException
and keep running. interrupt()
primarily sets a flag in the Thread
object, which you can check with isInterrupted()
. It also causes some methods -- sleep()
, join
Object.wait()
, in particular -- to return immediately by throwing an InterruptedException
. It also causes some I/O operations to immediately terminate. If you're seeing the printouts from your catch
block, then you can see that interrupt()
is working.
这篇关于为什么interrupt()没有按预期工作,它是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!