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();
            }
        }
    }
  • 相关阅读:
    最小化程序到托盘
    Delphi
    c# 多线程
    下载地址加密
    一个很让我郁闷的java异常
    XmlBeanFactory和ApplicationContext读取spring xml配置文件
    tomcat部署war出错的问题
    JAXB 实现List接口
    Mongo数据模型
    JAXB, Web Services, and Binary Data
  • 原文地址:https://www.cnblogs.com/moris5013/p/12038551.html
Copyright © 2011-2022 走看看