Java CompletableFuture的complete(7)
先看代码:
CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() { @Override public String get() { try { TimeUnit.SECONDS.sleep(2); } catch (Exception e) { e.printStackTrace(); } return "blog.csdn.net/zhangphil"; } }); System.out.println(System.currentTimeMillis() + ":time 1"); future.whenCompleteAsync(new BiConsumer<String, Throwable>() { @Override public void accept(String s, Throwable throwable) { System.out.println(System.currentTimeMillis() + ":" + s); } }); System.out.println(System.currentTimeMillis() + ":time 2"); new Thread(new Runnable() { @Override public void run() { try { TimeUnit.SECONDS.sleep(3); } catch (Exception e) { //异常退出。 future.completeExceptionally(e); } // CompletableFuture被通知线程任务完成。 System.out.println(System.currentTimeMillis() + ":运行至此。"); future.complete("任务完成。"); } }).start(); System.out.println(System.currentTimeMillis() + ":time 3");
输出:
06-19 11:25:17.630 15068-15068/zhangphil.test I/System.out: 1529378717630:time 1 06-19 11:25:17.631 15068-15068/zhangphil.test I/System.out: 1529378717631:time 2 1529378717631:time 3 06-19 11:25:19.638 15068-15094/zhangphil.test I/System.out: 1529378719638:blog.csdn.net/zhangphil 06-19 11:25:20.634 15068-15095/zhangphil.test I/System.out: 1529378720633:运行至此。
可以看到在Thread线程体中的
future.complete("任务完成。");
没有执行,是因为在CompletableFuture.supplyAsync只休息了两秒,就正常执行完毕了,故不再执行complete的代码了。complete用来告知CompletableFuture任务完成。
下面调换sleep时间,让CompletableFuture.supplyAsync休息的长一些,而Thread里面休息短一下:
CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() { @Override public String get() { try { TimeUnit.SECONDS.sleep(3); } catch (Exception e) { e.printStackTrace(); } return "blog.csdn.net/zhangphil"; } }); System.out.println(System.currentTimeMillis() + ":time 1"); future.whenCompleteAsync(new BiConsumer<String, Throwable>() { @Override public void accept(String s, Throwable throwable) { System.out.println(System.currentTimeMillis() + ":" + s); } }); System.out.println(System.currentTimeMillis() + ":time 2"); new Thread(new Runnable() { @Override public void run() { try { TimeUnit.SECONDS.sleep(2); } catch (Exception e) { //异常退出。 future.completeExceptionally(e); } // CompletableFuture被通知线程任务完成。 System.out.println(System.currentTimeMillis() + ":运行至此。"); future.complete("任务完成。"); } }).start(); System.out.println(System.currentTimeMillis() + ":time 3");
输出:
06-19 11:32:26.814 16768-16768/zhangphil.test I/System.out: 1529379146814:time 1 06-19 11:32:26.815 16768-16768/zhangphil.test I/System.out: 1529379146815:time 2 06-19 11:32:26.816 16768-16768/zhangphil.test I/System.out: 1529379146816:time 3 06-19 11:32:28.818 16768-16820/zhangphil.test I/System.out: 1529379148818:运行至此。 06-19 11:32:28.822 16768-16854/zhangphil.test I/System.out: 1529379148822:任务完成。
这次没有输出字符串blog.csdn.net/zhangphil了,因为Thread率先执行完成,则直接以complete的结果为准,忽略CompletableFuture.supplyAsync的get计算结果。