zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    }
  • 相关阅读:
    Linq to SQL -- 入门篇
    进程和线程(线程是轻量级进程)(上)
    复制文件夹中的所有文件夹与文件到另一个文件夹
    C# 特性(Attribute)
    文件的输入与输出
    正则表达式
    预处理指令
    String类
    可空类型(Nullable)
    参数传递
  • 原文地址:https://www.cnblogs.com/moris5013/p/12038551.html
Copyright © 2011-2022 走看看