利用completableFuture 事件回调解决
public static void main(String[] args) throws InterruptedException {
long l = System.currentTimeMillis();
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
System.out.println("在回调中执行耗时操作...");
Thread.sleep(10000);
}catch (Exception e){
e.printStackTrace();
}
return 100;
});
completableFuture = completableFuture.thenCompose(i -> {
return CompletableFuture.supplyAsync(() -> {
try{
System.out.println("在回调的回调中执行耗时操作...");
Thread.sleep(10000);
}catch (Exception e){
e.printStackTrace();
}
return i + 100;
});
});
completableFuture.whenComplete((result, e) -> {
System.out.println("计算结果:" + result);
});
System.out.println("主线程运算耗时:" + (System.currentTimeMillis() - l) + " ms");
new CountDownLatch(1).await();
} |