CompletableFuture是java1.8中追加的新功能,在处理java多线程异步时相当的方便,下面是简单的用法
简单的讲述了在非主线程中,执行完一个业务后接着执行另外一个业务的处理方法thenApplyAsync。
import java.util.concurrent.CompletableFuture;
public void testCompletableFuture() throws InterruptedException {
// 第一个任务:
CompletableFuture<String> cfQuery = CompletableFuture.supplyAsync(() -> {
return queryCode("济南东进");
});
// cfQuery成功后继续执行下一个任务:
CompletableFuture<Double> cfFetch = cfQuery.thenApplyAsync((code) -> {
return fetchPrice(code);
});
// cfFetch成功后打印结果:
cfFetch.thenAccept((result) -> {
System.out.println("price: " + result);
});
// 主线程不要立刻结束,否则CompletableFuture默认使用的线程池会立刻关闭:
Thread.sleep(2000);
}
String queryCode(String name) {
try {
Thread.sleep(100);
System.out.println("进入到 queryCode!");
} catch (InterruptedException e) {
}
return "601857";
}
Double fetchPrice(String code) {
try {
Thread.sleep(100);
System.out.println("进入到 fetchPrice!");
} catch (InterruptedException e) {
}
return 5 + Math.random() * 20;
}
执行结果,大家参考看一下执行的先后顺序
进入到 queryCode!
进入到 fetchPrice!
price: 21.125127372722343