Future,RunnableFuture,FutureTask学习

Future接口

public interface Future<V> {

	//取消任务执行 
	//当任务还没有启动,返回ture
	//当任务正在运行中,会根据mayInterruptIfRunning参数决定是否中断当前运行的线程来取消当前运行的任务
	//当任务已经完成或异常,其他一些原因不能中断时,返回false
    boolean cancel(boolean mayInterruptIfRunning);

	//判断任务完成之前是否被取消
	//只用当任务时未启动状态或完成之前被取消 该方法才会返回true,其他情况都返回false
    boolean isCancelled();

	//判断任务是否执行完成
	//异常退回,正常执行完成,被取消 都会返回true
    boolean isDone();

	//获取任务执行结果会异常
	//会阻塞等到结果返回
    V get() throws InterruptedException, ExecutionException;
	//同上 只不过设置了超时时间,超时之后会返回出TimeoutException异常
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

RunnableFuture

public interface RunnableFuture<V> extends Runnable, Future<V> {
	//任务
    void run();
}

FutureTask

public class FutureTask<V> implements RunnableFuture<V> {
	/**
	   线程可能变化的路线
	 * NEW -> COMPLETING -> NORMAL
     * NEW -> COMPLETING -> EXCEPTIONAL
     * NEW -> CANCELLED
     * 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;
    
    /** 需要执行的任务*/
    private Callable<V> callable;
    /**返回值 */
    private Object outcome; 
    /**运行任务的线程*/
    private volatile Thread runner;
    /**表示等待线程的堆栈,在FutureTask的实现中,会通过CAS结合此堆栈交换任务的运行状态。*/
    private volatile WaitNode waiters;
	
	//状态大于CANCELLED 都返回true 表示成功取消
    public boolean isCancelled() {
        return state >= CANCELLED;
    }
	//只要状态不是NEW 都返回true 表示任务执行完成
    public boolean isDone() {
        return state != NEW;
    }

	public boolean cancel(boolean mayInterruptIfRunning) {
		//状态不是NEW 或者CAS返回值是false 则直接返回false,表示取消任务失败
        if (!(state == NEW &&
              UNSAFE.compareAndSwapInt(this, stateOffset, NEW,
                  mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))
            return false;
        try {    //如果mayInterruptIfRunning参数是true,则将运行任务的线程中断
            if (mayInterruptIfRunning) {
                try {
                    Thread t = runner;
                    if (t != null)
                        t.interrupt();
                } finally { // final state
                //将状态置为INTERRUPTED
                    UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);
                }
            }
        } finally {
            finishCompletion();
        }
        return true;
    }
	
	private void finishCompletion() {
        // 定义一个循环 终止条件是waiters==null
        for (WaitNode q; (q = waiters) != null;) {
        	//CAS成功之后,进入自旋循环
            if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
                for (;;) {
                //取出线程
                    Thread t = q.thread;
                    if (t != null) {
                    //将线程置为null
                        q.thread = null;
                        //恢复该线程,让其运行完毕
                        LockSupport.unpark(t);
                    }
                    WaitNode next = q.next;
                    //判断如果next没有引用 则直接break
                    if (next == null)
                        break;
                    q.next = null; // unlink to help gc
                    q = next;
                }
              
                break;
            }
        }
		//子类实现
        done();
		//将任务置为null
        callable = null;        // to reduce footprint
    }

	public V get() throws InterruptedException, ExecutionException {
		//获取当前状态大于COMPLETING
        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)//如果超时 直接抛出TimeoutException异常
            throw new TimeoutException();
        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()) {//如果线程异常了,则直接抛出InterruptedException异常
                removeWaiter(q);
                throw new InterruptedException();
            }

            int s = state;
            if (s > COMPLETING) {//如果状态大于COMPLETING,不论是正常执行完成还是异常了,都是执行完成了
                if (q != null)
                    q.thread = null;//执行完成之后将执行任务线程置空,gc
                return s;//将完成任务之后的状态返回
            }
            //如果状态是 COMPLETING 则将线程礼让出去
            else if (s == COMPLETING) // cannot time out yet
                Thread.yield();
            else if (q == null)//如果WaitNode未空 则创建一个
                q = new WaitNode();
            else if (!queued)//CAS
                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);
        }
    }
	
	public void run() {
		//状态不是NEW 或者CAS为false 直接返回
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
        	//要执行的任务
            Callable<V> c = callable;
            //当前状态是NEW
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                	//调用call方法执行任务 接受返回值
                    result = c.call();
                    //将ran置为true
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                //代表正常执行,并且有返回值
                if (ran)
                //将返回值设置给outcome,并将状态更新
                    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);
        }
    }
}

你可能感兴趣的:(Java,java)