为什么interrupt()没有按预期工作,它是如何工作的

jas*_*son 5 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");
        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();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但输出看起来像thead1仍在运行.所以任何人都可以解释它,interrupt()如何工作,谢谢

Ern*_*ill 14

线程仍在运行,因为您捕获InterruptedException并继续运行.interrupt()主要在Thread对象中设置一个标志,您可以检查该标志isInterrupted().这也导致了一些方法- sleep(),join Object.wait()特别-立即抛出一个回归InterruptedException.它还会导致某些I/O操作立即终止.如果您看到catch块中的打印输出,那么您可以看到它interrupt()正常工作.


mre*_*mre 11

正如其他人所说,你抓住了中断,但没有采取任何措施.你需要做的是使用诸如的逻辑传播中断,

while(!Thread.currentThread().isInterrupted()){
    try{
        // do stuff
    }catch(InterruptedException e){
        Thread.currentThread().interrupt(); // propagate interrupt
    }
}
Run Code Online (Sandbox Code Playgroud)

使用循环逻辑,例如while(true)只是延迟编码.相反,轮询线程的中断标志以确定通过中断终止.

  • 是的,但@MByD已经提到了这一点,它保持了错误的循环逻辑.:d (2认同)