繁体   English   中英

Java:强制停止ExecutorService线程

[英]Java: Force stopping of ExecutorService threads

我的代码:


String[] torrentFiles = new File("/root/torrents/").list();

        if(torrentFiles.length == 0 || torrentFiles == null)
        {
            System.exit(0);
        }

        ex = Executors.newFixedThreadPool(3);

        for(String torrentFile : torrentFiles)
        {
            ex.submit(new DownloadTorrent("/root/torrents/" + torrentFile));
        }

        ex.shutdown();

        try
        {
            ex.awaitTermination(30, TimeUnit.MINUTES);
        }
        catch(InterruptedException ex1)
        {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex1);
        }

但有时洪流下载需要未知的时间价值,« awaitTermination »不能按我的意愿运行。 我需要在半小时后立即停止所有执行的线程,但据我所知« awaitTermination »只使用interrupt()方法,该方法仅在循环或等待中起作用。 如果这一刻发生,超时不起作用。 那么,怎么样?

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

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

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

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

这是javadoc的引用

List<Runnable> shutdownNow()

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

除尽力尝试停止处理主动执行任务之外,没有任何保证。 例如,典型的实现将通过Thread.interrupt()取消,因此如果任何任务屏蔽或无法响应中断,它们可能永远不会终止。

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

您还需要关闭底层套接字以取消阻塞IO,请参阅如何立即终止套接字IO操作上的线程阻塞?

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

使用我创建的代码。

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

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

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

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

我用了 :

  • 关掉()
  • shutdownNow()在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);
            }

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

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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM