Java并发编程的Callable、Futrue、FutureTask

在原有的多线程(Thread与Runable)上线程执行方法run()的返回值为void而在在并发包先使用Callable的Call方法的时候是有一个V范型返回。

Callable接口源码:

@FunctionalInterface
public interface Callable {
    V call() throws Exception;
}

这个接口是不同与Runable,在Runable中run方法是没有返回值的,而在Callable中要求返回一个传入的范型V,这里我们可以设计多线程的执行单元,同时返回一定的信息。

Future接口源码:

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

Futrue为线程提供五个能力,而这些能力为我们对线程的执行状态作出判断。

--cancel 还未执行完,可以取消线程执行

--get  获得执行的返回结果

--isDone 判断是否执行完

--isCancelled 判断计算是否别取消 

实现类FutrueTask实现RunableFutrue接口,而RunableFutrue接口继承啦Runable与Futrue接口,提供了五种Task的状态能够让我们时刻获取到线程的状态

	private volatile int state; // 注意volatile关键字
    /**
     * 在构建FutureTask时设置,同时也表示内部成员callable已成功赋值,
     * 一直到worker thread完成FutureTask中的run();
     */
    private static final int NEW = 0;

    /**
     * woker thread在处理task时设定的中间状态,处于该状态时,
     * 说明worker thread正准备设置result.
     */
    private static final int COMPLETING = 1;

    /**
     * 当设置result结果完成后,FutureTask处于该状态,代表过程结果,
     * 该状态为最终状态final state,(正确完成的最终状态)
     */
    private static final int NORMAL = 2;

    /**
     * 同上,只不过task执行过程出现异常,此时结果设值为exception,
     * 也是final state
     */
    private static final int EXCEPTIONAL = 3;

    /**
     * final state, 表明task被cancel(task还没有执行就被cancel的状态).
     */
    private static final int CANCELLED = 4;

    /**
     * 中间状态,task运行过程中被interrupt时,设置的中间状态
     */
    private static final int INTERRUPTING = 5;

    /**
     * final state, 中断完毕的最终状态,几种情况,下面具体分析
     */
    private static final int INTERRUPTED = 6;

state初始化为NEW。只有在set, setException和cancel方法中state才可以转变为终态。在任务完成期间,state的值可能为COMPLETING或INTERRUPTING。 
state有四种可能的状态转换:

     * NEW -> COMPLETING -> NORMAL

     * NEW -> COMPLETING -> EXCEPTIONAL

     * NEW -> CANCELLED

     * NEW -> INTERRUPTING -> INTERRUPTED

其他成员变量的含义:

    /** The underlying callable; nulled out after running */

    private Callable callable;   // 具体run运行时会调用其方法call(),并获得结果,结果时置为null.

 

    /** The result to return or exception to throw from get() */

    private Object outcome; // non-volatile, protected by state reads/writes   没必要为votaile,因为其是伴随state 进行读写,而state是FutureTask的主导因素。

 

    /** The thread running the callable; CASed during run() */

    private volatile Thread runner;   //具体的worker thread.

 

    /** Treiber stack of waiting threads */  

    private volatile WaitNode waiters;     //Treiber stack 并发stack数据结构,用于存放阻塞在该futuretask#get方法的线程。

Task的状态变化(Task的一个生命周期)

在FutureTask被创建的的时候首先构造函数确保Task的状态为NEW

    public FutureTask(Callable callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

注意:Runable转换成Callable的方法,其实就是通过Callable的call方法调用Runable的run方法,然后将传入的V返回。

    public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
}

 	public static  Callable callable(Runnable task, T result) {
        if (task == null)
            throw new NullPointerException();
        return new RunnableAdapter(task, result);
}

    static final class RunnableAdapter implements Callable {
        final Runnable task;
        final T result;
        RunnableAdapter(Runnable task, T result) {
            this.task = task;
            this.result = result;
        }
        public T call() {
            task.run();
            return result;
        }
}

在创建Task成功后,此时的Task的状态为NEW,然后调用FutureTask的run方法。

    public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable 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);//将状态设置为EXCEPTION
                }
                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);
        }
    }

在执行期间如果发生异常就会调用setException方法将状态设置为EXCEPTIONAL。

    protected void setException(Throwable t) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }

顺利完成就会调用set(result)方法将状态设置为NORMAL。

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

最后执行finishCompletion方法,会解除所有阻塞的worker thread, 调用done()方法,将成员变量callable设为null。这里使用了LockSupport类来解除线程阻塞。

    private void finishCompletion() {
        // assert state > COMPLETING;
        for (WaitNode q; (q = waiters) != null;) {
            if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
                for (;;) {
                    Thread t = q.thread;
                    if (t != null) {
                        q.thread = null;
                        LockSupport.unpark(t);
                    }
                    WaitNode next = q.next;
                    if (next == null)
                        break;
                    q.next = null; // unlink to help gc
                    q = next;
                }
                break;
            }
        }

        done();

        callable = null;        // to reduce footprint
    }

FutureTask的get方法,首先会判断是否为完成状态,如果是说明执行过set或setException方法啦,直接返回report,如果是未完成状态则会调用awaitDone去阻塞线程。

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

如果是NORMAL说明执行没有任何错误,所以通过get方法获得的就是执行返回的结果,如果是取消状态,说明调用过setException,则抛出CancellationException异常,否则抛出ExcecutionException异常。

   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);
    }

    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);
        }
}

awaiteDone简单的可以看做轮询查看FutureTask的状态。在执行awaiteDone期间(get阻塞期间):

1、如果执行get的线程被中断,则移除FutureTask的所有阻塞队列中的线程(waiters),并抛出中断异常;

2、如果FutureTask的状态转换为完成状态(正常完成或取消),则返回完成状态;

3、如果FutureTask的状态变为COMPLETING,则说明正在set结果,此时让线程等一等;

4、如果FutureTask的状态为初始态NEW,则当前线程加入到FutureTask的阻塞线程中去;

5、如果get方法没有设置超时时间,则阻塞当前调用get线程;如果设置了超时时间,则判断是否达到超时时间,如果达到,则移除FutureTask 的所有阻塞列队中的线程,并返回此时FutureTask的状态,如果未到达时间,则在剩下的时间内继续阻塞当前线程。

你可能感兴趣的:(------,【java深入理解】)