【问题标题】:interrupt() not working as expected (how does interrupt work?)中断()没有按预期工作(中断如何工作?)
【发布时间】:2011-11-08 12:18:56
【问题描述】:

我想中断一个线程,但调用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() 的工作原理吗?谢谢!

【问题讨论】:

    标签: java multithreading thread-safety interrupt-handling


    【解决方案1】:

    线程仍在运行只是因为您捕获了InterruptedException 并继续运行。 interrupt() 主要在Thread 对象中设置一个标志,您可以使用isInterrupted() 进行检查。它还会导致一些方法——特别是sleep()joinObject.wait()——通过抛出InterruptedException 立即返回。它还会导致一些 I/O 操作立即终止。如果您看到来自 catch 块的打印输出,那么您可以看到 interrupt() 正在工作。

    【讨论】:

      【解决方案2】:

      正如其他人所说,你抓住了中断,但什么也不做。您需要做的是使用逻辑传播中断,例如,

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

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

      【讨论】:

      • 或者您可以将 try/catch 移到循环之外。 ;)
      • 是的,但是@MByD 已经提到了这一点,它使糟糕的循环逻辑保持不变。 :D
      • +1 用于提及 while ( true ) 的替代方法谢谢!
      • @mre InterruptedException 是一个已检查的异常,如果 //do stuff 正在使用 Thread.sleep 它将起作用...否则呢?我需要强制使用 Thread.sleep 吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-23
      相关资源
      最近更新 更多