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();
            }
        }
    }
  • 相关阅读:
    HTML <iframe> 标签
    HTML <tr> 标签
    HTML <img> 标签的 border 属性
    jQuery ajax ajax() 方法
    CSS padding 属性
    SQL Server CONVERT() 函数
    CSS overflow 属性
    HTML <input> 标签
    Java动态代理一——动态类Proxy的使用
    Java拆箱装箱小结
  • 原文地址:https://www.cnblogs.com/moris5013/p/12038551.html
Copyright © 2011-2022 走看看