美文网首页
CompletableFuture简介

CompletableFuture简介

作者: 日落_3d9f | 来源:发表于2022-10-09 22:48 被阅读0次

    1、CompletableFuture之Future为什么出现

    CompletableFuture之Future为什么出现

    2、Future接口能干什么

    Future接口能干什么

    3、引出FutureTask

    FutureTask

    FutureTask支持构造注入,支持多线程/Callable有返回/Future异步任务特性。

        public FutureTask(Callable<V> callable) {
            if (callable == null)
                throw new NullPointerException();
            this.callable = callable;
            this.state = NEW;       // ensure visibility of callable
        }
    

    4、FutureTask案例

    代码:

    public class Main {
    
        public static void main(String[] arg) throws ExecutionException, InterruptedException {
            FutureTask<String> futureTask = new FutureTask<>(new myThread());
            Thread t1 = new Thread(futureTask, "t1");
            t1.start();
            System.out.println(futureTask.get());
        }
    }
    
    //Callable有返回
    class myThread implements Callable<String> {
    
        @Override
        public String call() throws Exception {
            System.out.println("-----come in call()");
            return "hello Callable";
        }
    }
    

    执行结果:

    -----come in call()
    hello Callable
    
    Process finished with exit code 0
    

    相关文章

      网友评论

          本文标题:CompletableFuture简介

          本文链接:https://www.haomeiwen.com/subject/dbrnartx.html