【发布时间】:2020-10-08 13:12:46
【问题描述】:
看看这段代码:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class InvokeAny {
public static void main(String[] args) {
Callable<String> callableTask = () -> {
TimeUnit.MILLISECONDS.sleep(300);
System.out.println("Callable task's execution");
return "Task's execution";
};
List<Callable<String>> callableTasks = new ArrayList<>();
callableTasks.add(callableTask);
callableTasks.add(callableTask);
callableTasks.add(callableTask);
ExecutorService executorService = Executors.newFixedThreadPool(2);
try {
executorService.invokeAny(callableTasks);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
shutdownAndAwaitTermination(executorService);
}
private static void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(1000, TimeUnit.MILLISECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!pool.awaitTermination(1000, TimeUnit.MILLISECONDS))
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
}
每次我运行我的程序时,我都会在控制台中得到不同的结果。
第一次运行:
Callable task's execution
第二次运行:
Callable task's execution
Callable task's execution
第三次运行:
Callable task's execution
谁能解释一下为什么会这样?
在 Oracle 的文档中,只有一个关于方法 invokeAny(Collection<? extends Callable<T>> tasks) 的短语:
执行给定的任务,返回一个任务的结果 成功完成(即没有抛出异常),如果有的话 做。
我想了解它是如何工作的。它是否会在完成一项后取消剩余的任务?如果是这样,为什么有时我会执行 2 个任务?
【问题讨论】:
-
您创建了一个带有
2线程的Executors.newFixedThreadPool()。所以我假设有 2 个任务被提交,有时它们可能同时完成(或不完成),让你得到这个结果。并发取决于可能不同的因素。例如。 JVM 正在做什么以及 你的 计算机在后台做什么。这样一来,一项任务可能会比另一项更快或更慢地完成
标签: java multithreading executorservice java.util.concurrent