CompletabelFuture 泡茶喝
public class DrinkTea {
private static final int SLEEP_CAP = 3000;
public static void main(String[] args) {
final long l = System.currentTimeMillis();
var hotJob = CompletableFuture.supplyAsync(() -> {
System.out.println("洗好水壶了");
System.out.println("烧开水");
sleepSeconds(SLEEP_CAP);
return true;
});
var washJob = CompletableFuture.supplyAsync(() -> {
System.out.println("洗茶杯");
sleepSeconds(SLEEP_CAP);
System.out.println("茶杯洗完了");
return true;
});
var drinkJob = hotJob.thenCombine(washJob,
(hodOk, washOk) -> {
if (hodOk && washOk) {
System.out.println("泡茶喝, 茶喝完");
return "茶喝完了";
}
return "没有喝到茶";
});
System.out.println(drinkJob.join());
System.out.println("time = " + (System.currentTimeMillis() -l));
}
private static void sleepSeconds(int sleepCap) {
try {
Thread.sleep(sleepCap);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
控制台输出
洗好水壶了
烧开水
洗茶杯
茶杯洗完了
泡茶喝, 茶喝完
茶喝完了
time = 3008
浙公网安备 33010602011771号