前言
Future接口有一定的局限性,比如,我们很难表述Future结果之间的依赖性,因此在Java8中引入了CompletableFuture,它针对Future做了改进,可以传入回调对象,当异步任务完成或者发生异常时,自动调用回调对象的回调方法。
CompletableFuture对象的创建
Java8中提供了4个静态方法用来创建CompletableFuture对象,具体介绍分别如下:
通过静态方法创建CompletableFuture对象
- 创建一个异步线程,参数为Runnable,它的返回值为Void,内部使用的是默认的ForkJoinPool.commonPool()线程池
public static CompletableFuture<Void> runAsync(Runnable runnable) {
return asyncRunStage(asyncPool, runnable);
}
- 先比于1,CompletableFuture也提供了通过指定线程池的方式来创建它的对象,如下:
public static CompletableFuture<Void> runAsync(Runnable runnable,Executor executor) {
return asyncRunStage(screenExecutor(executor), runnable);
}
- 上面1,2通过runAsync方式创建的CompletableFuture对象都是没有返回值的,如果需要有返回值的,需要用到它的supplyAsync方法,如下:
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
return asyncSupplyStage(asyncPool, supplier);
}
- 同样,也可以通过指定线程池的方式传参,如下:
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier,Executor executor) {
return asyncSupplyStage(screenExecutor(executor), supplier);
}
示例
//无返回值
private static void testRunAsync() throws Exception {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
log.info("testRunAsync begin run...");
doSomething();
log.info("testRunAsync run end...");
});
Void aVoid = future.get();
}
//有返回值
private static void testSupplyAsync() throws Exception {
CompletableFuture<Long> future = CompletableFuture.supplyAsync(() -> {
log.info("testSupplyAsync begin run...");
doSomething();
log.info("testSupplyAsync run end...");
return System.currentTimeMillis();
});
long time = future.get();
log.info("future get:" + time);
}
private static void doSomething() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
log.info("exception:{}", e.getMessage());
}
}