我想中断一个线程,但是调用interrupt()似乎不起作用。以下是示例代码:
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()是如何工作的吗?谢谢!
发布于 2011-11-08 20:20:46
线程仍然在运行,这很简单,因为您捕获了InterruptedException并保持运行。interrupt()主要在Thread对象中设置一个标志,您可以使用isInterrupted()对其进行检查。它还会导致一些方法--特别是sleep()、join Object.wait() --通过抛出InterruptedException而立即返回。它还会导致某些I/O操作立即终止。如果您看到来自catch块的打印输出,那么您可以看到interrupt()正在工作。
发布于 2011-11-08 21:05:53
正如其他人所说,你捕捉到了中断,但什么也不做。您需要做的是使用以下逻辑传播中断:
while(!Thread.currentThread().isInterrupted()){
try{
// do stuff
}catch(InterruptedException e){
Thread.currentThread().interrupt(); // propagate interrupt
}
}使用循环逻辑,如while(true),只是惰性编码。取而代之的是,轮询线程的中断标志,以便通过中断确定终止。
https://stackoverflow.com/questions/8050235
复制相似问题