zoukankan      html  css  js  c++  java
  • Future FutrueTask Callable类源码说明以及原理使用

     正文前先来一波福利推荐:

     福利一:

    百万年薪架构师视频,该视频可以学到很多东西,是本人花钱买的VIP课程,学习消化了一年,为了支持一下女朋友公众号也方便大家学习,共享给大家。

    福利二:

    毕业答辩以及工作上各种答辩,平时积累了不少精品PPT,现在共享给大家,大大小小加起来有几千套,总有适合你的一款,很多是网上是下载不到。

    获取方式:

    微信关注 精品3分钟 ,id为 jingpin3mins,关注后回复   百万年薪架构师 ,精品收藏PPT  获取云盘链接,谢谢大家支持!

    -----------------------正文开始---------------------------

    1、Future Callable FutureTask 源码说明

      JDK内置的Future主要使用到了Callable接口和FutureTask类。

      Callable是类似于Runnable的接口,实现Callable接口的类和实现Runnable的类都是可被其他线程执行的任务。Callable接口的定义如下:

    复制代码
    public interface Callable<V> {
    /**
    * Computes a result, or throws an exception if unable to do so.
    *
    * @return computed result
    * @throws Exception if unable to compute a result
    */
    V call() throws Exception;
    }
    复制代码

      Callable的类型参数是返回值的类型。例如:

    Callable<Integer>表示一个最终返回Integer对象的异步计算。

      Future保存异步计算的结果。实际应用中可以启动一个计算,将Future对象交给某个线程,然后执行其他操作。Future对象的所有者在结果计算好之后就可以获得它。Future接口具有下面的方法:

    复制代码
    public interface Future<V> {
        boolean cancel(boolean mayInterruptIfRunning);
        boolean isCancelled();
        boolean isDone();
        V get() throws InterruptedException, ExecutionException;
        V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
    }
    复制代码

     

    get & get(long timeout, TimeUnit unit)

      第一个get方法的调用被阻塞,直到计算完成。如果在计算完成之前,第二个get方法的调用超时,抛出一个TimeoutException异常。如果运行该计算的线程被中断,两个方法都将抛出InterruptedException。如果计算已经完成,那么get方法立即返回。

    isDone

      如果计算还在进行,isDone方法返回false;如果完成了,则返回true。

    cancel:

      可以用cancel方法取消该计算。如果计算还没有开始,它被取消且不再开始。如果计算处于运行之中,那么如果mayInterrupt参数为true,它就被中断

      true : 任务状态= INTERRUPTING = 5。如果任务已经运行,则强行中断。如果任务未运行,那么则不会再运行

      false:CANCELLED = 4。如果任务已经运行,则允许运行完成(但不能通过get获取结果)。如果任务未运行,那么则不会再运行

    isCancelled
      判断是够被取消;

      FutureTask包装器是一种非常便利的机制,同时实现了Future和Runnable接口。FutureTask有2个构造方法

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

    下面具体分析下FutureTask的实现,先看JDK8的,再比较一下JDK6的实现。

    既然FutureTask也是一个Runnable,那就看看它的run方法

    public void run() {
            if (state != NEW ||
                !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                             null, Thread.currentThread()))
                return;
            try {
                Callable<V> c = callable; // 这里的callable是从构造方法里面传人的
                if (c != null && state == NEW) {
                    V result;
                    boolean ran;
                    try {
                        result = c.call();
                        ran = true;
                    } catch (Throwable ex) {
                        result = null;
                        ran = false;
                        setException(ex); // 保存call方法抛出的异常
                    }
                    if (ran)
                        set(result); // 保存call方法的执行结果
                }
            } finally {
                // runner must be non-null until state is settled to
                // prevent concurrent calls to run()
                runner = null;
                // state must be re-read after nulling runner to prevent
                // leaked interrupts
                int s = state;
                if (s >= INTERRUPTING)
                    handlePossibleCancellationInterrupt(s);
            }
        }

    这里表示状态的属性state是个什么鬼

    复制代码
         // Possible state transitions:

        //1)执行过程顺利完成:NEW -> COMPLETING -> NORMAL

        //2)执行过程出现异常:NEW -> COMPLETING -> EXCEPTIONAL

        //3)执行过程被取消:NEW -> CANCELLED

        //4)执行过程中,线程中断:NEW -> INTERRUPTING -> INTERRUPTED

        private volatile int state;
        private static final int NEW          = 0;
        private static final int COMPLETING   = 1;
        private static final int NORMAL       = 2;
        private static final int EXCEPTIONAL  = 3;
        private static final int CANCELLED    = 4;
        private static final int INTERRUPTING = 5;
        private static final int INTERRUPTED  = 6;
    复制代码

    get方法:

        public V get() throws InterruptedException, ExecutionException {
            int s = state;
            if (s <= COMPLETING)
                s = awaitDone(false, 0L);
            return report(s);
        }
    复制代码
        private int awaitDone(boolean timed, long nanos)
            throws InterruptedException {
            final long deadline = timed ? System.nanoTime() + nanos : 0L;
            WaitNode q = null;
            boolean queued = false;
            for (;;) {
    /** 这里的if else的顺序也是有讲究的。
    1.先判断线程是否中断,中断则从队列中移除(也可能该线程不存在于队列中)
    2.判断当前任务是否执行完成,执行完成则不再阻塞,直接返回。
    3.如果任务状态=COMPLETING,证明该任务处于已执行完成,正在切换任务执行状态,CPU让出片刻即可
    4.q==null,则证明还未创建节点,则创建节点
    5.q节点入队
    6和7.阻塞 **/

    if (Thread.interrupted()) { removeWaiter(q); throw new InterruptedException(); } int s = state; if (s > COMPLETING) { if (q != null) q.thread = null; return s; } else if (s == COMPLETING) // cannot time out yet Thread.yield(); else if (q == null) q = new WaitNode(); else if (!queued) queued = UNSAFE.compareAndSwapObject(this, waitersOffset, q.next = waiters, q); else if (timed) { nanos = deadline - System.nanoTime(); if (nanos <= 0L) { removeWaiter(q); return state; } LockSupport.parkNanos(this, nanos); } else LockSupport.park(this); } }
    复制代码

    可以看到get方法中使用了for循环,在任务没有执行完成return之前,一直处于阻塞状态,通过阻塞当前线程,直至run方法执行完成,state状态变为大于 COMPLETING

    下边看一下report方法;

    private V report(int s) throws ExecutionException {
            Object x = outcome;
            if (s == NORMAL)
                return (V)x;
            if (s >= CANCELLED)
                throw new CancellationException();
            throw new ExecutionException((Throwable)x);
        }

    cancel方法:

     mayInterruptIfRunning用来决定任务的状态。
        true : 任务状态= INTERRUPTING = 5。如果任务已经运行,则强行中断。如果任务未运行,那么则不会再运行
        false:CANCELLED    = 4。如果任务已经运行,则允许运行完成(但不能通过get获取结果)。如果任务未运行,那么则不会再运行
        **/
        public boolean cancel(boolean mayInterruptIfRunning) {
            if (state != NEW)
                return false;
            if (mayInterruptIfRunning) {
                if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
                    return false;
                Thread t = runner; //调用 Thread.interrupt()强行中断
                if (t != null)
                    t.interrupt();
                UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
            }
            else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
                return false;
            finishCompletion(); //如果任务已经执行 则执行完成(但不能通过get获取结果)
         return true; 
    }
  • 相关阅读:
    [转载]Centos7.x下环境搭建(一)--yum方式安装mysql5.7
    树上分治
    [SPOJ2666]QTREE4
    [SPOJ375]QTREE
    [SPOJ1825]FTOUR2
    [POJ1741]Tree
    [LG-P5350]序列
    [COCI 2014/2015 #3]KAMIONI
    [SHOI2014]神奇化合物
    [GXOI/GZOI2019]旧词
  • 原文地址:https://www.cnblogs.com/gxyandwmm/p/9393364.html
Copyright © 2011-2022 走看看