实例
提供 Callable 列表
/**
* 获取 Callable 列表
*
* @return
*/
private List<Callable<Integer>> getCallableList() {
List<Callable<Integer>> list = new ArrayList<>(3);
for (int i = 3; i >= 1; i--) {
int current = i;
list.add(() -> {
int millis = current * 1000;
Thread.sleep(millis);
System.out.println(String.format("Thread %s finish in %s", current, millis));
return current;
});
}
return list;
}
使用 ExecutorService 完成异步任务
/**
* 使用 ExecutorService 完成异步任务
* 不能先完成先知道结果
*/
@Test
public void test_executorService() throws Exception {
ExecutorService es = Executors.newFixedThreadPool(4);
List<Callable<Integer>> callableList = getCallableList();
List<Future<Integer>> futureList = new ArrayList<>(3);
for (Callable<Integer> callable : callableList) {
futureList.add(es.submit(callable));
}
for (Future<Integer> future : futureList) {
System.out.println(String.format("the result is %s", future.get()));
}
}/* 最后一个完成前边才能获取结果
Thread 1 finish in 1000
Thread 2 finish in 2000
Thread 3 finish in 3000
the result is 3
the result is 2
the result is 1
*/
使用 CompletionService 完成异步任务
/**
* 使用 CompletionService 完成异步任务
* 先完成的先输出结果
* @throws Exception
*/
@Test
public void test_completionService() throws Exception {
CompletionService<Integer> cs = new ExecutorCompletionService<>(
Executors.newFixedThreadPool(4));
List<Callable<Integer>> callableList = getCallableList();
for (Callable<Integer> callable : callableList) {
cs.submit(callable);
}
for (int i = 0; i < callableList.size(); i++) {
Future<Integer> future = cs.take();
System.out.println(String.format("the result is %s", future.get()));
}
}/* 先完成的先输出结果
Thread 1 finish in 1000
the result is 1
Thread 2 finish in 2000
the result is 2
Thread 3 finish in 3000
the result is 3
*/
CompletionService 方法分析
待补充
CompletionService 源码分析
待补充