Java:强制停止ExecutorService线程 [英] Java: Force stopping of ExecutorService threads

查看:1833
本文介绍了Java:强制停止ExecutorService线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:


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()只能在循环或等待中工作的方法。因此,如果发生这种情况,超时不起作用那么,怎么样?

But sometimes torrent downloading takes unknown time value and «awaitTermination» not works as I want. I need to stop all executed threads instantly after half an hour but as I know «awaitTermination» just only use interrupt() method which works only in loops or waiting. So timeout not works if this moment happens. So, how to?

推荐答案

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

ExecutorService.shutdownNow() will try to stop all the executing threads..

这是来自javadoc的报价

Here is a quote from javadoc


列表与LT;可运行> shutdownNow()

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

Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

除了尽力尝试停止
处理主动执行任务之外,没有保证

例如,典型的实现
将通过Thread.interrupt()取消,所以
如果任何任务掩盖或无法响应
中断,它们可能永远不会
终止。

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so if any tasks mask or fail to respond to interrupts, they may never terminate.

这篇关于Java:强制停止ExecutorService线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆