java并发学习04---Future模式

因为Future模式在日常看到的代码中用的比较多,因此就先小结下这个模式,后面再来看并发容器中的集合类。java

 

JDK中的Future模式:并发

Future,既是将来的意思,那么这个模式的意思呢,就是说这个任务我如今并不会立刻作完,你如今先去作点别的,等我作好了再通知你,联系“将来“ 这个词的意思就是说在未来的某个时刻,我把东西作好了,而后再返回给你。app

先来看一下类图:ide

(FutureTask 和 Callable之间应该还有一个依赖关系,可是)ui

经过类图咱们能够知道:spa

Future是一个接口,拥有get方法,你经过get()方法能够能够取得返回值,而RunnableFuture接口 在继承Future接口的同时又继承了Runnable接口,那么RunnableFuture又能够做为Runnable对象开启一个线程,FutureTask类则实现了这些方法。线程

 

代码演示:code

用了官网的代码,为了方便演示添加了一些输出的语句对象

import java.util.concurrent.*;

public class Lesson01_Future {
    public static void main(String[] args) throws InterruptedException {
        Callable searcher = new Callable() {
            @Override
            public String call() throws Exception {
                System.out.println("一个耗时大概5s的操做开始暗中进行\n");
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < 5; i++) {
                    sb.append(i);
                    Thread.sleep(1000);
                }
                return sb.toString();
            }
        };

        ExecutorService excutor = Executors.newFixedThreadPool(1);

        FutureTask<String> future = new FutureTask<String>(searcher);

        //这里searcher就开始执行了
        excutor.submit(future);
        Thread.sleep(100);   //确保searcher已经开始执行

        //在searcher执行的时候,咱们能够去干点别的
        //使用一个sleep方法模拟一个耗时操做
        System.out.println("等待的时候我们干点别的,");
        for (int i = 0; i < 3 ; i++) {
            System.out.println("other things: " + (i+1) + "s");
            Thread.sleep(1000);
        }
        System.out.println("other things 搞定,如今去看看耗时的操做搞完没\n");

        //如今再来看它搞定没,搞定了就输出它的值
        //注意没搞定的话,线程就必须阻塞在这里等着它搞定,不能继续去作其余的事情了
        try {
            if(future.isDone()) {
                System.out.println("耗时的操做已经完成,结果是:" + future.get());
            } else {
                System.out.println("耗时操做尚未完成,我们再等等");
                System.out.println("耗时的操做已经完成,结果是:" + future.get());
            }
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        excutor.shutdown();
    }
}

向线程池提交searcher以后,模拟的耗时操做就开始进行了,而后主线程仍是能够执行其余的任务,可是一旦你使用了future.get()方法,线程就必须阻塞住直到future返回结果为止。blog

 

最后的执行结果:

一个耗时大概5s的操做开始暗中进行

等待的时候我们干点别的,
other things: 1s
other things: 2s
other things: 3s
other things 搞定,如今去看看耗时的操做搞完没

耗时操做尚未完成,我们再等等
耗时的操做已经完成,结果是:01234

Process finished with exit code 0
相关文章
相关标签/搜索