【发布时间】:2015-01-20 17:27:10
【问题描述】:
我有一个接受新任务的执行器服务:
ExecutorService executor = Executors.newFixedThreadPool(1000);
//stupid example with several parralel tasks
for (int i = 0; i < 1000; i++) {
try{
Runnable task = new Runnable() {
public void run() {
throw new RuntimeException("foo");
}
};
executor.submit(task);
}
catch (ExecutionException e) {
System.out.println(e.getMessage());
}
}
我的问题是我无法捕获 Runnable 抛出的任何异常,除非我这样做:
Future<?> future = executor.submit(task);
try {
future.get();
} catch (Exception e) {
System.out.println("############### exception :" + e.getMessage());
}
问题是future.get() 是阻塞的,所以如果我不能异步运行我的任务,我的任务将不会并行运行,而是按顺序运行。
我希望能够使用 Java 8 和 CompletableFuture,但我不能... 你有什么其他想法吗?
谢谢
【问题讨论】:
-
为什么不先发送所有任务运行,然后收集结果?
-
因为在我的实际项目中,它不是循环,而是用户操作,所以任务不断到达
标签: java concurrency