• CompletableFuture3


    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();
            }
        }
    }
  • 相关阅读:
    OpenWRT解决因PPPOE丢包导致频繁掉线问题
    ArcGIS Server 9.3集群部署(多som+多soc)
    ArcGIS Server 9.3集群部署(多som+多soc)
    POJ2823 滑动窗口
    AOJ 0531 坐标离散化
    Office2010安装错误
    Cv运动分析与对象跟踪(转)
    FPS学习记录
    opencv基于HSV的肤色分割
    Haar特征
  • 原文地址:https://www.cnblogs.com/moris5013/p/12038551.html
Copyright © 2020-2023  润新知