异步任务交互方法applyToEither,acceptEither和runAfterEither的使用介绍.
1. applyToEither两个异步任务哪个先返回就处理哪个异步任务结果并返回CompletableFuture
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
SecureRandom random = new SecureRandom();
int x = random.nextInt(3);
CommonUtil.sleepSecond(x);
CommonUtil.printThreadLog("任务1耗时: "+x);
return "result1";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
SecureRandom random = new SecureRandom();
int x = random.nextInt(3);
CommonUtil.sleepSecond(x);
CommonUtil.printThreadLog("任务2耗时: "+x);
return "result2";
});
CompletableFuture<String> toEither = future1.applyToEither(future2, (res) -> {
CommonUtil.printThreadLog("最先到达: " + res);
return res;
});
String str = toEither.get();
CommonUtil.printThreadLog(str);
![在这里插入图片描述](https://img-blog.csdnimg.cn/d9533fd246db4e7fa3c878a1601c27e7.png)
2. acceptEither两个异步任务哪个先返回就处消费哪个异步任务结果,无返回值.
CommonUtil.printThreadLog("main start");
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
SecureRandom random = new SecureRandom();
int x = random.nextInt(3);
CommonUtil.sleepSecond(x);
CommonUtil.printThreadLog("耗时: "+x);
return "result1";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
SecureRandom random = new SecureRandom();
int x = random.nextInt(3);
CommonUtil.sleepSecond(x);
CommonUtil.printThreadLog("耗时: "+x);
return "result2";
});
future1.acceptEither(future2, (res) -> {
CommonUtil.printThreadLog("最先到达: " + res);
});
CommonUtil.printThreadLog("main continue");
//主线程等任务结束
CommonUtil.sleepSecond(4);
runAfterEither两个异步任务哪个任务先结束,就会收到一个Runnable通知
CommonUtil.printThreadLog("main start");
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
SecureRandom random = new SecureRandom();
int x = random.nextInt(3);
CommonUtil.sleepSecond(x);
CommonUtil.printThreadLog("耗时: "+x);
return "result1";
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
SecureRandom random = new SecureRandom();
int x = random.nextInt(3);
CommonUtil.sleepSecond(x);
CommonUtil.printThreadLog("耗时: "+x);
return "result2";
});
future1.runAfterEither(future2, () -> {
CommonUtil.printThreadLog("一个任务完成");
});
CommonUtil.printThreadLog("main continue");
CommonUtil.sleepSecond(4);