线程在Java中应该如何关闭自身?

2022-08-31 14:11:29

这是一个简短的问题。在某些时候,我的线程明白它应该自杀。最好的方法是什么:

  1. Thread.currentThread().interrupt();
  2. 返回;

顺便说一句,为什么在第一种情况下我们需要使用?是否不是指当前线程?currentThreadThread


答案 1

如果要终止线程,则只需返回即可。你不需要打电话(它不会做任何坏事。只是你不需要。这是因为基本上用于通知线程的所有者(好吧,不是100%准确,而是某种程度上)。因为你是线程的所有者,并且你决定终止线程,所以没有人通知,所以你不需要调用它。Thread.currentThread().interrupt()interrupt()

顺便说一句,为什么在第一种情况下我们需要使用currentThread?线程不是指当前线程吗?

是的,它没有。我想这可能会令人困惑,因为例如Thread.sleep()会影响当前线程,但Thread.sleep()是一种静态方法。

如果您不是线程的所有者(例如,如果您尚未扩展和编码等),则应执行ThreadRunnable

Thread.currentThread().interrupt();
return;

这样,任何调用 runnable 的代码都将知道线程已中断 = (通常)应停止它正在执行的任何操作并终止。正如我之前所说,它只是一种沟通机制。所有者可能只是忽略中断状态,不执行任何操作。但是,如果您确实设置了中断状态,将来可能会有人为此感谢您。

出于同样的原因,你永远不应该这样做

Catch(InterruptedException ie){
     //ignore
}

因为如果你这样做,你就是在那里停止消息。相反,一个人应该做

Catch(InterruptedException ie){
    Thread.currentThread().interrupt();//preserve the message
    return;//Stop doing whatever I am doing and terminate
}

答案 2

如果 run 方法结束,线程将结束。

如果使用循环,正确的方法如下:

// In your imlemented Runnable class:
private volatile boolean running = true;

public void run()
{
   while (running)
   {
      ...
   }
}


public void stopRunning()
{
    running = false;
}

当然,返回是最好的方法。