CompletableFuture简介

1、CompletableFuture之Future为什么出现

CompletableFuture之Future为什么出现

2、Future接口能干什么

Future接口能干什么

3、引出FutureTask

FutureTask

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

    public FutureTask(Callable 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 futureTask = new FutureTask<>(new myThread());
        Thread t1 = new Thread(futureTask, "t1");
        t1.start();
        System.out.println(futureTask.get());
    }
}

//Callable有返回
class myThread implements Callable {

    @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简介)