Java 中断()未按预期工作(中断如何工作?)
我想中断线程,但调用Java 中断()未按预期工作(中断如何工作?),java,multithreading,thread-safety,interrupt-handling,Java,Multithreading,Thread Safety,Interrupt Handling,我想中断线程,但调用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");
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()
是如何工作的吗?谢谢 线程仍在运行,只是因为您捕获了InterruptedException
并继续运行interrupt()
主要在Thread
对象中设置一个标志,您可以使用isInterrupted()
进行检查。它还导致一些方法--sleep()
,join
对象。wait()
,特别是--。它还会导致一些I/O操作立即终止。如果您看到的是catch
块中的打印输出,则可以看到interrupt()
正在工作。正如其他人所说,您捕获了中断,但对其不做任何处理。您需要做的是使用如下逻辑传播中断:
while(!Thread.currentThread().isInterrupted()){
try{
// do stuff
}catch(InterruptedException e){
Thread.currentThread().interrupt(); // propagate interrupt
}
}
使用循环逻辑,例如
而(true)
只是惰性编码。相反,轮询线程的中断标志,以便通过中断确定终止。或者您可以将try/catch移到循环之外。;)是的,但@MByD已经提到了这一点,它保持了糟糕的循环逻辑完好无损D+1,感谢您提及while(true)
p.s.的替代方法。谢谢@mre InterruptedException是一个选中的异常,如果//do stuff正在使用Thread.sleep,它将工作……否则呢?我需要线程睡眠强制吗?