Callable和FutureTask

171 阅读2分钟

Callable

  • CallableRunnable我理解都是任务需要一个Thread来驱动。
  • Runnable里的run方法返回值为void。并且方法签名上没有抛出异常。所以我们重写的run方法是不能抛出异常的

重写父类的方法,访问权限得比父类大。但是不能抛出更大的异常

/**
 * A task that returns a result and may throw an exception.
 * Implementors define a single method with no arguments called
 * {@code call}.
 *
 * <p>The {@code Callable} interface is similar to {@link
 * java.lang.Runnable}, in that both are designed for classes whose
 * instances are potentially executed by another thread.  A
 * {@code Runnable}, however, does not return a result and cannot
 * throw a checked exception.
 *
 * <p>The {@link Executors} class contains utility methods to
 * convert from other common forms to {@code Callable} classes.
 *
 * @see Executor
 * @since 1.5
 * @author Doug Lea
 * @param <V> the result type of method {@code call}
 */
@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;
}
  • 可见源码注释写的已经很详细了。

FutureTask

Thread构建的时候可以传Runnable但是不能传Callable

这时候出现了FutureTask

  • FutureTask继承了RunnableFuture。再往上继承了Runnable。所以一个FutureTask是可以被Thread接收的。
  • 构造方法
    // 可以接收callable对象
    public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }
    // 也可以接收runnable对象
    public FutureTask(Runnable runnable, V result) {
        // Executors是一个工具类。能够把runnable转换成一个callable
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }
  • FutureTaskrun方法中调用的是callable.call()所以一切都一目了然了。

FutureTask的get方法是怎么得到异步结果的呢

  • 一个FutureTask中有volatile int state
    // 注意这是在另一个线程中执行的。不是跑任务的线程
    public V get() throws InterruptedException, ExecutionException {
        // state会一直在变化的,这s=state就是保存了一个快照,总是这么玩
        int s = state;
        // 如果没完成呢 就等
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        // 如果完成了,通过report包装结果返回
        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 (Thread.interrupted()) {
                removeWaiter(q);
                throw new InterruptedException();
            }
            // 还是同样的玩法 保存一个快照
            int s = state;
            if (s > COMPLETING) {
                if (q != null)
                    q.thread = null;
                return s;
            }
            // 这是Thread.yield的最有证明的例子
            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
                // get没完成的时候会阻塞住。
                LockSupport.park(this);
        }
    }
  • 如果我们在main线程中调用了futureTask.get会观察state的值。
  • 如果完成了直接拿到结果。如果没完成,park。