在Concurrent框架

时间:2016-07-19 16:05:58

标签: java executorservice java.util.concurrent executors

如果我使用Futures喜欢

List<Future<String>> results = executorService.invokeAll(tasks); 

Future<String> res = executorService.submit(new SingleWorker());
System.out.println(res.get());

系统等待任务完成。

即使我在上述陈述之后有executorService.shutdownNow();,我真的不明白系统何时强制终止文档中提到的现有线程,因为系统永远不会到达行任务完成,返回未来。 我错过了什么吗?是否有不同的测试用例场景来测试它?

shutdownNow只会Runnable使用,即我们说的时候 executorService.submit(new MyRunnable())

修改

我尝试了几件不同的东西,发现了

a)shutdownNow不适用于invokeAll

b)shutdownNow如果在Future.get之后出现,则语句shutdownNow被屏蔽,直到 Future被解决(如果{{1} }})。

c)CallableshutdownNow完美契合。

以下是我的代码写入测试:

Runnable

我正在测试它如下:

class SingleRunnableWorker implements Runnable {

    @Override
    public void run() {
        System.out.println("SingleRunnableWorker Running..");
        try {
            Thread.sleep(10000);
            System.out.println("SingleRunnableWorker Running after sleep..");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

class SingleCallableWorker implements Callable<String> {

    @Override
    public String call() throws Exception {
        System.out.println("SingleCallableWorker Calling..");
        Thread.sleep(10000);
        System.out.println("SingleCallableWorker Calling after sleep..");
        return "SingleCallableWorker Calling done";
    }

}

其中任务都是ExecutorService executorService = Executors.newFixedThreadPool(4); /*List<Future<String>> results = */executorService.invokeAll(tasks);//blocks by default Future<String> res = executorService.submit(new SingleCallableWorker()); //System.out.println(res.get()); //blocks if uncommented executorService.submit(new SingleRunnableWorker()); executorService.shutdownNow();

底线是CallablesinvokeAll是阻止操作。有人可以验证吗?

1 个答案:

答案 0 :(得分:1)

您提交给Runnbale的{​​{1}}和Callable都将被ThreadPoolExecutor包围并执行。

在这种情况下,在java.util.concrrent.FutureTaskSingleRunnableWorker中,当任务被SingleCallableWorker阻止时,Thread.sleep(10000)将导致立即抛出InterruptedException。

但是,

    {li> executorService.shutdownNow()投放在InterruptedException中 被迫立即被抓获并由SingleRunnableWorker.run()处理。 {li> e.printStackTrace()InterruptedException投入 由同步器SingleCallableWorker.call()中的内部同步器捕获 记录InterruptedException并返回。调用FutureTask时, InterruptedException将作为ExecutionException和 重新抛出。