在ExecutorService的isCancelled()中返回true的原因

时间:2019-06-13 14:41:06

标签: java executorservice

isCancelled()true中使用callable()方法执行.invokeAll()时给了我ExecutorService标志。如果我尝试使用.submit(),请给我false。使用invokeAll()方法时实现真相是什么?

ExecutorService executorService = 
Executors.newSingleThreadExecutor();

Set<Callable<String>> callables = new. 
HashSet<Callable<String>>();

callables.add(new Callable<String>() {
    public String call() throws Exception {
        executeCommand();
    return "Task 1";
 }
});
callables.add(new Callable<String>() {
     public String call() throws Exception {
         executeCommand();
    return "Task 2";
 }
});
callables.add(new Callable<String>() {
    public String call() throws Exception {
         executeCommand();
    return "Task 3";
}
});

List<Future<String>> futures = 
executorService.invokeAll(callables);

for(Future<String> future : futures){
    System.out.println(future.isCancelled());
    System.out.println("future.get = " + future.get());
}

executorService.shutdown();

考虑上面的示例,其中executeCommand()具有一些逻辑,可以执行并行封装在作业周围的代码。我使用isCancelled()方法实现了。使用ExecutorService.submit(),结果为false。

请帮助。

1 个答案:

答案 0 :(得分:0)

相应的答案在正确的ExecutorService documentation中进行了解释:

  • invokeAll:执行给定任务,返回期货列表,在所有完成或超时到期时(以先发生者为准)保存其状态和结果。

    < / li>
  • submit:提交一个Runnable任务以执行并返回一个Future ,代表该任务的挂起结果。

相关问题