阅读背景:

CompletableFuture、ListenableFuture高级用列

来源:互联网 

CompletableFuture
链式

public static void main(String[] args) throws Exception { CompletableFuture<Integer> thenCompose = T1() .thenCompose(Compress::T2) .thenCompose(Compress::T3); Integer result = thenCompose.get(); System.out.println(result); } // 假设这些是异步操作,并返回CompletableFuture<Integer> public static CompletableFuture<Integer> T1() { return CompletableFuture.supplyAsync(() -> { // 模拟耗时操作 try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } return 1; }); } public static CompletableFuture<Integer> T2(int valueFromT1) { return CompletableFuture.supplyAsync(() -> { // 使用上一步的结果进行计算 int result = valueFromT1 * 2; try { Thread.sleep(500); } catch (InterruptedException e) { throw new RuntimeException(e); } return result; }); } public static CompletableFuture<Integer> T3(int valueFromT2) { return CompletableFuture.supplyAsync(() -> { // 使用上一步的结果进行计算 int finalResult = valueFromT2 + 10; return finalResult; }); } public static void main(Strin



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: