如何杀死有一段时间(true)的线程?

max*_*mus 12 java multithreading thread-safety threadpool

我试图在我的线程池中关闭所有线程.

通常我会尝试:

        while(!Thread.currentThread().isInterrupted()) {...
Run Code Online (Sandbox Code Playgroud)

关闭while循环...

但我有一个仅包含的线程

        while(!Thread.currentThread().isInterrupted()) {//which is true
Run Code Online (Sandbox Code Playgroud)

这是我关闭线程的方式:

pool.shutdownNow();
Run Code Online (Sandbox Code Playgroud)

那你怎么关闭这样一个线程呢?

Ami*_*nde 15

您可以添加volatile布尔值flag.

public class Worker implements Runnable {

    volatile boolean cancel = false;
    @Override
    public void run() {

        while (!cancel) {
            // Do Something here
        }
    }

    public void cancel() {
        cancel = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以打电话了

worker.cancel();
Run Code Online (Sandbox Code Playgroud)

更新:

从Java doc of shutdownNow()

尝试停止所有正在执行的任务,停止等待任务的处理,并返回等待执行的任务列表.

除了尽力尝试停止处理主动执行任务之外,这里不能保证.例如,典型的实现将通过Thread.interrupt()取消,因此任何未能响应中断的任务都可能永远不会终止.

因此,您必须通过保留中断来定义中断策略

  catch (InterruptedException ie) {
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
Run Code Online (Sandbox Code Playgroud)

  • 在我看来,第一条建议是"检查它被吞噬的地方",并且只作为最后的手段使用自定义机制,因为这涉及更多的代码,为代码带来失败的新方法. (3认同)
  • -1这是多余的 - 为什么不仅使用中断机制? (2认同)