前言
在业务处理过程中,会经常使用到多线程进行异步处理,日常情况下就会开启一个线程,直接执行。但在有些情况下,我们需要获取到异步执行的结果, jdk 1.5以后新引入了Future和Callable,可以方便的获取异步线程的执行结果,本文使用代码进行演示。
1.使用future 获取异步结果
public class Test {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newFixedThreadPool(20);
List<Future> futureList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
// 使用executorService提交异步线程任务,future整合结果
Future<String> future = executorService.submit(count(i));
futureList.add(future);
}
// future.get时才为阻塞获取线程执行结果的时候
for (Future future : futureList) {
System.out.println(future.get());
}
}
static Callable<String> count(final int i) {
return new Callable