中断()未按预期工作(中断如何工作?) [英] interrupt() not working as expected (how does interrupt work?)
问题描述
我想中断一个线程,但调用 interrupt()
似乎不起作用.下面是示例代码:
I want to interrupt a thread, but invoking interrupt()
doesn't seem to 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();
}
}
}
}
但输出看起来线程 1 仍在运行.谁能解释这个以及 interrupt()
是如何工作的?谢谢!
but the output looks like thread 1 is still running. Can anyone explain this as well as how interrupt()
works? Thanks!
推荐答案
线程仍在运行仅仅是因为您捕获 InterruptedException
并继续运行.interrupt()
主要在 Thread
对象中设置一个标志,您可以使用 isInterrupted()
进行检查.它还导致一些方法——特别是sleep()
、join
Object.wait()
——通过抛出一个<代码>中断异常代码>.它还导致一些 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.
这篇关于中断()未按预期工作(中断如何工作?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!