从JDK 8开始,在Concurrent包中提供了⼀个强⼤的异步编程⼯具CompletableFuture。在JDK8之前,异步编程可以通过线程池和Future来实现,但功能还不够强⼤。
1.基本用法
CompletableFuture<String> future = new CompletableFuture<>();
new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
future.complete("hello world");
}).start();
System.out.println("获取结果中。。。");
String result = future.get();
System.out.println("获取的结果:" + result);
}
}
2.runAsync与supplyAsync
runAsync:用于异步执行任务,无需返回结果
CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(()
-> {
try {
Thread.sleep(2000);
System.out.println("任务执⾏完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// 阻塞,等待任务执⾏完成
voidCompletableFuture.get();
System.out.println("程序运⾏结束");
}
supplyAsync:用于异步执行任务,需要返回结果
CompletableFuture<String> future = CompletableFuture.supplyAsync(new
Supplier<String>() {
@Override
public String get() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "这是结果";
}
});
String result = future.get();
System.out.println("任务执⾏结果:" + result);
}
3.thenRun、thenAccept和thenApply
对于 Future,在提交任务之后,只能调⽤ get()等结果返回;但对于 CompletableFuture,可以在结果上⾯再加⼀个callback,当得到结果之后,再接着执⾏callback。
thenRun、thenAccept和thenApply都可以加在supplyAsync的后面,不能加在runAsync后。
- thenRun后⾯跟的是⼀个⽆参数、⽆返回值的⽅法,即Runnable,所以最终的返回值是CompletableFuture类型。
- thenAccept后⾯跟的是⼀个有参数、⽆返回值的⽅法,称为Consumer,返回值也是CompletableFuture类型。顾名思义,只进不出,所以称为Consumer;前⾯的Supplier,是⽆参数,有返回值,只出不进,Consumer刚好相反。
- thenApply 后⾯跟的是⼀个有参数、有返回值的⽅法,称为Function。返回值是CompletableFuture类型。
4.thenCompose和thenCombine
- thenCompose:如果使用了thenApply方法,当我们用get()方法获取返回值时,这时返回的又是一个CompletableFuture,我们需要再调用一次get()方法来获取里面的值。而用thenCompose的话可以使其“扁平化”,
CompletableFuture<CompletableFuture<T>> x = CompletableFuture.supplyAsync(..).thenSupply(..)
就变成了
CompletableFuture<T> x = CompletableFuture.supplyAsync(..).thenCompose(..)
- thenCombine:当有两个CompletableFuture时,我希望把它俩的结果拿来运算产生一个新的结果时,可以用到thenCombine来实现。
CompletableFuture<T> x = CompletableFuture.supplyAsync(..).thenCombine(CompletableFuture.supplyAsync(..),new BitFunction(..,T));
4.CompletableFuture的allOf()和anyOf()
两个方法都可以传任意多个CompletableFuture对象,allOf表示当所有CompletableFuture都执行完后再执行(个人感觉有点像CountdownLatch),anyOf表示当传入的CompletableFuture组里有一个执行完后就执行。
5. CompletableFuture的原理
CompletableFuture内部使用了ForkJoinPool来处理提交的任务,ForkJoinPool 是JDK 7加入的一个线程池类,它可以将传入的任务转化为ForkJoinTask并使用它独有的Fork/Join机制来异步执行这些任务。
ForkJoinPool:使用了分治算法思想,和普通线程的区别不同的是,它内部的全局队列不是BlockingQueue,而是一个普通数组,并且在此基础上多了局部队列,每个执行线程都会有它自己的局部队列,分治算法会将一个任务拆分成多个子任务分别加入这些局部队列,达到高效任务处理的目的,并且还使用了队列窃取机制来实现任务的负载均衡。