CompletableFuture抛弃了JDK7及以前的基于线程池的异步任务,而是CompletableFuture.runAsync这样的静态工厂方法来返回一个CompletableFuture对象。它既支持JDK7的Future/Callback模型,也支持新的异步任务执行回调和合并操作。在JDK8以前,也有一些框架实现了这种类型的Future。比如,guava的ListenableFuture和Netty的ComputeFuture和ComputeFutureListener。
值得注意的是,CompletableFuture也不再使用Callable作为可返回的任务接口,而是使用Supplier接口。
下面是一个有返回值的示例,调用get方法会被阻塞,直到Run方法执行完毕:
public class TestFuture {
public static void main(String[] args) throws InterruptedException, ExecutionException {
System.out.println(Thread.currentThread().getName());
CompletableFuture cf1 = CompletableFuture.runAsync(new Runnable() {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName());
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
cf1.get();
System.out.println("执行完毕");
}
}
输出:
main
ForkJoinPool.commonPool-worker-1
执行完毕
CompletableFuture使用的默认的线程池在任务执行完成以后所有的线程退出。
CompletableFuture也可以指定线程池对象:
public class TestFuture {
public static void main(String[] args) throws InterruptedException, ExecutionException {
System.out.println(Thread.currentThread().getName());
Supplier task = new Supplier() {
@Override
public String get() {
try {
System.out.println(Thread.currentThread().getName());
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello";
}
};
CompletableFuture cf = CompletableFuture.supplyAsync(task, Executors.newFixedThreadPool(10));
System.out.println(cf.get());
System.out.println("执行完毕");
}
}
输出:
main
pool-1-thread-1
hello
执行完毕
但是要注意的是,使用默认的线程池,工作线程在任务执行完毕以后不会退出。
你可能会好奇,每次都执行一个任务,那如果要执行10次任务怎么办?下面是一个例子:
public class TestFuture3 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
System.out.println(Thread.currentThread().getName());
ExecutorService threadPool = Executors.newFixedThreadPool(10);
Supplier task = new Supplier() {
@Override
public String get() {
try {
System.out.println(Thread.currentThread().getName());
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello";
}
};
System.out.println(CompletableFuture.supplyAsync(task, threadPool).get());
System.out.println(CompletableFuture.supplyAsync(task, threadPool).get());
System.out.println(CompletableFuture.supplyAsync(task, threadPool).get());
System.out.println(CompletableFuture.supplyAsync(task, threadPool).get());
System.out.println(CompletableFuture.supplyAsync(task, threadPool).get());
System.out.println(CompletableFuture.supplyAsync(task, threadPool).get());
System.out.println(CompletableFuture.supplyAsync(task, threadPool).get());
System.out.println("执行完毕");
}
}
当然这会存在一个问题,就是所有都是串行执行的。
为什么非要得到结果?
使用Future得到结果的原因是因为要拿到这个结果进行下一个步骤的处理。但是如果能够在处理完成以后就能立即回调一个方法,或者几个并行的处理能够合并在一起。结果只在最后一个获取,是不是好很多。
假设有这样一个需求:
有一批订单号,需要查询这批订单的详情,评论,订单所对应商品的图片,然后合并成一个对象返回到客户端。
功能异乎寻常的强大,简直是吊打原有的Future/Callable模型。再配合流操作,简直要逆天,非常值得学习。
public class TestFuture {
public static void main(String[] args) throws InterruptedException, ExecutionException {
CompletableFuture cf1 = CompletableFuture.runAsync(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
System.out.println("hello CompletableFuture! ");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, Executors.newSingleThreadScheduledExecutor());
cf1.thenRun(new Runnable() {
@Override
public void run() {
System.out.println("异步执行完了,就执行这里!");
}
});
System.out.println("主线程执行完毕");
CompletableFuture result = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "async CompletableFuture! ";
}, Executors.newSingleThreadScheduledExecutor());
result.thenAccept((str) -> {
System.out.println("thenAccept");
System.out.println(str);
});
System.out.println("主线程执行完毕");
}
}
public class TestFuture3 {
public static void main(String[] args) throws InterruptedException, ExecutionException {
System.out.println(Thread.currentThread().getName());
ExecutorService threadPool = Executors.newFixedThreadPool(10);
Supplier> task = () -> {
System.out.println(Thread.currentThread().getName());
System.out.println("执行得到订单ID");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
List list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
return list;
};
/**
* Lambda方法的参数是apply方法的参数。不是类的参数
*/
Function, List> getOrder = (orderIds) -> {
System.out.println("开始执行得到订单,订单数:" + orderIds.size());
List orders = new ArrayList<>();
for (String string : orderIds) {
try {
Thread.sleep(100);
Order order = new Order();
order.setOrderId(string);
orders.add(order);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("完成执行得到订单,订单数:" + orders.size());
return orders;
};
CompletableFuture> cf = CompletableFuture.supplyAsync(task, threadPool);
CompletableFuture> cf1 = cf.thenApplyAsync(getOrder);
CompletableFuture> cf2 = cf.thenApplyAsync(orderIds -> {
List comments = new ArrayList<>();
System.out.println("执行输出订单,订单数:" + orderIds.size());
for (String orderId : orderIds) {
Comment comment = new Comment(orderId, "非常好");
comments.add(comment);
}
return comments;
});
CompletableFuture> resultCF = cf.thenCombine(cf1, (orderIds, orders) -> {
List details = new ArrayList<>();
for (Order order : orders) {
Detail detail = new Detail();
detail.setOrder(order);
detail.setOrderId(order.getOrderId());
details.add(detail);
}
return details;
}).thenCombine(cf2, (details, comments) -> {
for (Detail detail : details) {
for (Comment comment : comments) {
if (comment.getOrderId().equals(detail.getOrderId())) {
detail.setComment(comment);
}
}
}
return details;
});
List result = resultCF.get();
for (Detail detail : result) {
System.out.println(detail);
}
}
}
CompletableFuture的一系列接口操作,是非常接近人类思维的。但是对于程序员来说,越是接近人类的思维,代码反而难以理解。或许是因为对其接口掌控越来越弱,程序员对难以掌控的实现就好像有一种天生的排斥。就好像很多程序员都喜欢C++一样,因为程序员可以掌控一切吧。