美文网首页
FutureTask源码分析

FutureTask源码分析

作者: 汇源可乐 | 来源:发表于2019-11-10 19:59 被阅读0次

FutureTask的使用示例

  static class MyCallable implements Callable {
        @Override
        public Object call() throws Exception {
            return 10086;
        }
    }

 public static void threadExamples() {
        MyCallable myCallable = new MyCallable();
        FutureTask<Integer> ft = new FutureTask<>(myCallable);
        new Thread(ft).start();
        try {
            System.out.println(ft.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

console输出:    10086


以下部分为FutureTask源码分析


Callable接口

package java.util.concurrent;
/**@param <V> the result type of method 
 */
@FunctionalInterface
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;
}

thread 的构造函数

 public Thread(Runnable target) {
        init(ThreadGroup:null, target, "Thread Name", stackSize:0);
    }

\color{blue}{Thread} 的构造方法中我们可以看出,\color{blue}{Thread} 需要一个\color{blue}{Runnable} 参数,而\color{blue}{FutureTask} 是一个\color{blue}{Runnable} 的实现类吗?我们先看一下下面这段代码和\color{chocolate}{UML} 类图

public class FutureTask<V> implements RunnableFuture<V> 
public interface RunnableFuture<V> extends Runnable, Future<V> 
uml

从代码源码中我们可以看出\color{blue}{FutureTask} 实现了\color{blue}{RunnableFuture} 接口,而\color{blue}{RunnableFuture} 接口继承自\color{red}{Runnable}接口和\color{lime}{Future}接口

Thread源码部分——run方法

  @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

\color{blue}{Thread}\color{green}{run()} 方法可以得知,\color{green}{run()} 方法内部其实就是调用了target的\color{green}{run()}方法 ,在第三种实现方式里

FutureTask<V>的run方法

 public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = 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);
                }
                if (ran)
                    set(result);
            }
        } 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);
        }
    }

\color{blue}{FutureTask}\color{green}{run()}方法里就是回调了\color{blue}{Callable}\color{green}{call()}方法,我们知道\color{blue}{Callable}其实是一个接口,所以最终还是在他的实现类里实现,而我们自己定义了一个\color{blue}{MyCallable}类实现了\color{blue}{Callable}接口,在call里我们可以写上自己的一系列操作,然后返回一个对象给\color{blue}{FutureTask}\color{green}{run()}方法里的\color{gray}{result},然后调用\color{green}{set(V)}方法,将\color{gray}{result}对象设置给\color{gray}{outcome} \color{gold}{\{set方法在下面贴出了代码\}}

FutureTask的set方法和get方法
 protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();
        }
    }

 public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }

  public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }
FutureTask的report方法
@SuppressWarnings("unchecked")
    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);
    }

从上面的代码可以看出,我们调用\color{blue}{FutureTask}的对象的\color{green}{get()}方法,\color{green}{get()}方法会去调用\color{green}{report()}方法返回\color{plum}{outcome},而\color{green}{get()}方法不是立刻返回的,他会等待我们的\color{green}{call()}函数执行完成才会返回,调用\color{green}{get()}的线程才会继续执行,因为\color{green}{get()}方法里有一个阻塞式的方法。他会判断\color{green}{call()}函数的执行是否结束,没有结束就会调用\color{green}{awaitDone()}方法,\color{green}{awaitDone()}方法会根据是否有时间限制,如果有,在时钟到达前都会阻塞调用\color{green}{get()}的线程,如果始终已经到达,但是\color{green}{call()}方法还是没有执行完,那么就抛出一个\color{salmon}{TimeoutException},如果\color{green}{get()}不带时间限制,那么他就会调用 \color{green}{LockSupport.park(this)}方法阻塞调用\color{green}{get()}的线程

    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 (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);
        }
    }
LockSupport的park方法
public static void park(Object blocker) {
        Thread t = Thread.currentThread();
        setBlocker(t, blocker);
        UNSAFE.park(false, 0L);
        setBlocker(t, null);
    }

相关文章

网友评论

      本文标题:FutureTask源码分析

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