CompletableFuture 打桌球的应用
作者:互联网
CompletableFuture 使用
@Test public void billiardTest() throws Exception { // 创建点外卖线程: CompletableFuture<Boolean> takeaway = CompletableFuture.supplyAsync(() -> { System.out.println("开始点外卖"); try { System.out.println("外卖 => 下单"); Thread.sleep(1000); System.out.println("外卖 => 店家接单开始做饭"); Thread.sleep(10000); System.out.println("外卖 => 做饭完成骑手接单"); Random random = new Random(); int time = random.nextInt(5); Thread.sleep(time * 1000); System.out.println("外卖 => 外卖已送达"); } catch (InterruptedException e) { e.printStackTrace(); } return true; }); //创建打球线程 CompletableFuture<Boolean> billiard = takeaway.supplyAsync(() -> { System.out.println("开始打桌球"); //直接用线程的返回值,不用中间变量,防止变量被篡改 while (!takeaway.getNow(false)) { try { System.out.println("打球 => 摆球"); Thread.sleep(1000); System.out.println("打球 => 打球"); Thread.sleep(5000); System.out.println("打球 => 打球结束确定输赢"); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("外卖已到,不再打球"); return true; }); //打球的结束,依赖外卖,所以这边只需要看打球是否结束来确定是不是开始吃饭 billiard.thenAccept((param) -> { System.out.println("开始吃饭"); }); //主线程可以做其它事 while (true) { System.out.println("主线程可以做其它事:" + DateUtil.now()); Thread.sleep(1000); } }
标签:桌球,System,外卖,打球,CompletableFuture,应用,println,sleep,out 来源: https://www.cnblogs.com/vipsoft/p/16579534.html