簡介
上一篇寫了CompletableFuture的一些常用方法,今天看看CompletableFuture的一些不是很常用的方法,至少我是不常用…接着上篇講,上篇最後我記得提過allof,和anyof方法
allof,anyof方法
allof顧名思義,就是所有的任務執行完成後返回future,
anyif就是只要有一個任務執行完成後就返回future並將第一個完成的參數帶着一起返回,
代碼:
@Test
public void allOfTest1() throws Exception {
CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "f1";
});
CompletableFuture<String> f2 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
// throw new RuntimeException("aa");
return "f2";
});
CompletableFuture<Void> all = CompletableFuture.allOf(f1, f2).thenApply(x -> {
System.out.println("all");
return null;
});
//阻塞,直到所有任務結束。任務complete就會執行,handler裏面不一定會執行..
System.out.println(System.currentTimeMillis() + ":阻塞");
//join 或者get
Void aVoid = all.get();
System.out.println(System.currentTimeMillis() + ":阻塞結束");
//一個需要耗時2秒,一個需要耗時3秒,只有當最長的耗時3秒的完成後,纔會結束。
System.out.println("任務均已完成。");
}
執行結果:
如果異常也是直接報錯.
如果想處理異常,可以直接處理,可以通過whencomplete,handler方法…
anyof
同理,直接上代碼;
@Test
public void anyOfTest() throws Exception {
CompletableFuture<String> f1 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "f1";
});
CompletableFuture<String> f2 = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
// throw new RuntimeException("aa");
return "f2";
});
CompletableFuture<Object> anyof = CompletableFuture.anyOf(f1, f2).handle((x, y) -> {
System.out.println(x);
return x;
});;
//阻塞,直到所有任務結束。任務complete就會執行,handler裏面不一定會執行..
anyof.get();
//一個需要耗時2秒,一個需要耗時3秒,只有當最長的耗時3秒的完成後,纔會結束。
System.out.println("任務均已完成。");
}
返回結果:
如果是f1先返回那參數就是f1,如果是異常,那麼異常就帶過來了…