是否应该使用isInterrupted()方法停止线程的run方法中的while循环?



使用线程的isInterrupted()方法从外部调用interrupt()方法来结束run方法中的while循环,这是一个好做法吗?

public class ThreadManager{
    ...
    ...
    Thread t;
    public void init(){
      t = new MyThread();
      t.start();
    }
    .....
    public void stopProcessing(){
      t.interrupt();
    }
}
public class MyThread extends Thread{
     public void run(){
           while( !isInterrupted()){
              try{
                  //.. some process in a loop
              }catch(InterruptedException e){
                 // now stop running and end run method
              }
           }

     }
}

基本上,在大多数情况下,是的。在while循环中使用isInterrupted()作为条件是一种很好的做法,但这通常不是您需要做的全部。

在许多情况下,您还需要捕获InterruptedException,这表明interrupt()被调用。其中一种情况可能是在循环中使用Thread.sleep()。如果线程正在睡眠或等待,则必须捕获此异常。例如,可以在catch块中使用break

public void run() {
    while(!isInterrupted()) {
        try {
            ...
            sleep(1000L);
        } catch (InterruptedException ex) {
            break;
        }
    }
}

这可能是一个意见问题。在我的意见(这就是它的全部),是的,使用中断作为通知线程关闭的手段是一个好主意。

我很少有机会编写任何应用程序的顶层。我编写库代码。我总是假设interrupt()意味着我的代码应该优雅地中止它被要求做的任何事情,但它应该准备以防顶层应用程序要求它在之后再次执行某些操作。

如果我的代码创建了一个线程,并且线程中发生了中断,我通过让线程关闭自己来"中止",但我确保我的代码可以在需要时重新创建线程。

这样,如果顶层应用程序的设计者希望interrupt()表示"关闭应用程序",我的代码就可以处理它;但是,如果顶层应用的设计者希望它的含义不同(例如,中止当前命令,并提示用户执行另一个命令),那么我的代码也可以这样做。

最新更新