public class CompletableFuture3 { public static void main(String[] args) throws ExecutionException, InterruptedException { // testJoin(); testCompletableException(); } /** * completeExceptionally可以使得get方法不会阻塞,如果future没有完成,那调用get方法会抛出异常 * @throws ExecutionException * @throws InterruptedException */ public static void testCompletableException() throws ExecutionException, InterruptedException { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { sleep(5); System.out.println("======="); return "hello"; }); sleep(1); future.completeExceptionally(new Exception()); System.out.println(future.get()); } /** * 获取结果时,与get的区别是get会抛出检查异常,join不会抛出检查异常 */ public static void testJoin(){ CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { sleep(5); System.out.println("======="); return "hello"; }); String result = future.join(); System.out.println(result); } private static void sleep(int sec){ try { TimeUnit.SECONDS.sleep(sec); } catch (InterruptedException e) { e.printStackTrace(); } } }