会导致线程阻塞
public static void main(String[] args) throws Exception { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); ThreadUtil.execAsync(() -> { list.forEach(integer -> { if (IntegerUtils.equals(integer, 3)) { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { //模拟异步请求第三方接口 Thread.sleep(6000); } catch (InterruptedException e) { throw new RuntimeException(e); } return "已完成"; }).exceptionally(error -> { error.printStackTrace(); return "异步异常!"; }); String s = null; try { s = future.get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } System.out.println("异步后的结果:" + s); } System.out.println("integer:" + integer); }); }); System.out.println("主线程执行"); Scanner scanner = new Scanner(System.in); System.out.println("请输入:"); int i = scanner.nextInt(); System.out.println("内容是:" + i); }
当循环到3时,线程会进入睡眠,这时候会导致4和5堵塞,只有线程睡眠时间结束才会执行后面的操作
future.whenComplete不会导致线程阻塞
public static void main(String[] args) throws Exception { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); ThreadUtil.execAsync(() -> { list.forEach(integer -> { if (IntegerUtils.equals(integer, 3)) { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(6000); } catch (InterruptedException e) { throw new RuntimeException(e); } return "已完成"; }); future.whenComplete((s, exception) -> { System.out.println("异步后的结果:" + s); System.out.println("异常:" + exception); }); } System.out.println("integer:" + integer); }); }); System.out.println("主线程执行"); Scanner scanner = new Scanner(System.in); System.out.println("请输入:"); int i = scanner.nextInt(); System.out.println("内容是:" + i); }
从输出的顺序就可以看出,当循环到3时线程进入睡眠,并不会影响4和5的操作