CompletableFuture演示Future功能
public class CompeltableFutureUseDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService threadPool = Executors.newFixedThreadPool(3); CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> { System.out.println(Thread.currentThread().getName()+"--------come in"); int result = ThreadLocalRandom.current().nextInt(10); try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("--------1秒钟后出结果:"+result); return result; },threadPool); System.out.println(Thread.currentThread().getName()+"线程先去忙别的任务"); System.out.println(completableFuture.get()); } }
演示完成一个阶段后将值穿个下一个阶段
public class CompeltableFutureUseDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService threadPool = Executors.newFixedThreadPool(3); try{ CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> { System.out.println(Thread.currentThread().getName()+"--------come in"); int result = ThreadLocalRandom.current().nextInt(10); try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("--------1秒钟后出结果:"+result); return result; },threadPool).whenComplete((v,e)->{ if(e==null){ System.out.println("------计算完成,更新系统updateValue:"+v); } }).exceptionally(e->{ e.printStackTrace(); System.out.println("异常情况:"+e.getCause()+"\t"+e.getMessage()); return null; }); System.out.println(Thread.currentThread().getName()+"线程先去忙别的任务"); }catch (Exception e){ e.printStackTrace(); }finally{ threadPool.shutdown(); } } }
演示异常
public class CompeltableFutureUseDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService threadPool = Executors.newFixedThreadPool(3); try{ CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> { System.out.println(Thread.currentThread().getName()+"--------come in"); int result = ThreadLocalRandom.current().nextInt(10); try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("--------1秒钟后出结果:"+result); if(result>1){ int i = 10/0; } return result; },threadPool).whenComplete((v,e)->{ if(e==null){ System.out.println("------计算完成,更新系统updateValue:"+v); } }).exceptionally(e->{ e.printStackTrace(); System.out.println("异常情况:"+e.getCause()+"\t"+e.getMessage()); return null; }); System.out.println(Thread.currentThread().getName()+"线程先去忙别的任务"); }catch (Exception e){ e.printStackTrace(); }finally{ threadPool.shutdown(); } } }
返回结果:
CompletableFuture的优点
- 异步任务结束后,会自动回调某个对象的方法
- 主线程设置好回调后,不再关心异步任务的执行,异步任务之间可以顺序执行
- 异步任务出错时,会自动回调某个对象的方法