Java:强制停止ExecutorService线程

时间:2011-05-10 07:22:54

标签: java multithreading executorservice

6 个答案:

答案 0 :(得分:7)

永远不会保证即时线程终止,除非线程定期检查isInterrupted()标志(或者在可中断的方法中等待,即抛出InterruptedException)。

在定期检查isInterrupted()时,请考虑以方式实现工作线程。这可能是这样的:

public void run() { 
  byte[] data;
  do {
     data = receiveDataChunk(timeout);
     processData(data);
  } while(!isInterrupted() && data != null);
}

答案 1 :(得分:6)

ExecutorService.shutdownNow()将尝试停止所有正在执行的线程..

以下是javadoc的引用

  

List<Runnable> shutdownNow()

     

试图积极地停止所有活动   执行任务,停止处理   等待任务,并返回一个列表   等待的任务   执行。

     

没有保证   超越尽力而为的努力   处理积极执行的任务。   例如,典型的实现   将通过Thread.interrupt()取消,所以   如果任何任务掩盖或无法响应   中断,他们可能永远不会   终止。

答案 2 :(得分:6)

由于下载torrent可能涉及阻止IO操作,因此仅调用cancel() / shutdownNow()是不够的,因为阻止IO操作不能保证在各自的线程中断时终止。

您还需要关闭底层套接字以取消阻止IO,请参阅How to terminate a thread blocking on socket IO operation instantly?

答案 3 :(得分:1)

ExecutorService.submit(...)会返回Future<?>cancel()方法。您应该跟踪这些可以在您希望每项任务停止时调用它。

答案 4 :(得分:0)

使用我创建的代码。

使用 wkhtmltopdf 从许多html模板生成许多pdf文件。

所以我想提高创建handred的性能而不让客户端等待,这只是实现的一部分。

关于 getListOfCallables ,它返回正确的最佳值 在固定池创建中使用的线程数的阈值。

所以我无法处理周围有很多未死线程,这就是我的EC2 CPU 100%卡住了。

我用过:

  • shutdown()方法
  • shutdownNow()in else of await
  • 例外部分中的shutdownNow()

列出fileGenerationHtmlToPdfList = getListOfCallables(路径,名称,选项);

            ExecutorService executorService = Executors.newFixedThreadPool(fileGenerationHtmlToPdfList.size());


            List<Future<ArrayList<File>>> futures = null;

            try {
                futures = executorService.invokeAll(fileGenerationHtmlToPdfList);
                try {
                    for(Future f: futures) {
                        files.addAll((ArrayList<File>)f.get());
                    }

                } catch (InterruptedException ex) {
                    Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, "Interrupted Exception " , ex);
                } catch (ExecutionException ex) {
                    Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, "Interrupted Exception " , ex);
                }
            } catch (InterruptedException ex) {
                Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, "Interrupted Exception " , ex);
            }

 executorService.shutdown();//try shutdown

            try {
                if (executorService.awaitTermination(5, TimeUnit.SECONDS)) {
                    Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, "Done ShutDowned");
                } else {
                    executorService.shutdownNow();
                }
            } catch (InterruptedException ex) {
                executorService.shutdownNow();
                Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, "Interrupted Exception " , ex);
            }

答案 5 :(得分:-1)

现在我必须从池中停止线程。我是这样做的。这可能不是一个好主意。请评论,如果是的话。

boolean isTerminated = mPoolThreads.isTerminated();
while (!isTerminated) {
    mPoolThreads.shutdownNow();
    isTerminated = mPoolThreads.isTerminated();
    Log.i(Constants.LOG_TAG, "Stop threads: the threads are not terminated yet");
}
Log.w(Constants.LOG_TAG, "Stop threads: Terminated");