FutureTask

Future是我们在使java实现异步时最常用到的一个类,我们可以向线程池提交一个Callable,并通过future对象获取执行结果 。

Future

Future是一个接口,它定义了5个方法:

(1)boolean cancel(boolean mayInterruptIfRunning):取消一个任务,并返回取消结果。参数表示是否中断线程。

(2)boolean isCancelled():判断任务是否被取消。

(3)boolean isDone():判断当前任务是否执行完毕,包括正常执行完毕、执行异常或者任务取消。

(4)V get():获取任务执行结果,任务结束之前会阻塞。

(5)V get(long timeout,TimeUnit unit):在指定时间内尝试获取执行结果 。若超时则抛出超时异常。

 

 

 

public class FutureDemo {
      public static void main(String[] args) {
          ExecutorService executorService = Executors.newCachedThreadPool();
          Future future = executorService.submit(new Callable<Object>() {
              @Override
              public Object call() throws Exception {
                  Long start = System.currentTimeMillis();
                  while (true) {
                      Long current = System.currentTimeMillis();
                     if ((current - start) > 1000) {
                         return 1;
                     }
                 }
             }
         });
  
         try {
             Integer result = (Integer)future.get();
             System.out.println(result);
         }catch (Exception e){
             e.printStackTrace();
         }
     }
} 


这里模拟了1s钟的CPU空转,当执行future.get()的时候,主线程阻塞了大约一秒后获得结果 。

 

 

FutureTask

1.类继承结构

FutureTask实现了RunnableFuture接口,而RunnableFuture继承了Runnable和Future,也就是说FutureTask既是Runnable,也是Future。

 

2.核心成员变量

(1)volatile int state:表示对象状态,futureTask中定义了7种状态:

 

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; //任务线程已中断


(2)Callable<V> callable:被提交的任务。

 

(3)Object outcome:任务执行结果或者任务异常。

(4)volatile Thread runner:执行任务的线程。

(5)volatile WaitNode waiters:等待节点,关联等待线程。

(6)long stateOffset:state字段的内存偏移量

(7)long runnerOffset:runner字段的内存偏移量。

(8)long waitersOffset:waiters字段的内存偏移量。

后三个字段是配合Unsafe类做CAS操作使用的。

3.内部状态转换

FutureTask中使用state表示任务状态,state值变更由CAS操作保证原子性。

(1)任务正常执行并返回。NEW->COMPLETING->NORMAL

(2)执行中出现异常。NEW->COMPLETING->EXCEPTIONAL

(3)任务执行过程中被取消,并且不响应中断。NEW->CANCELLED

(4)任务执行过程中被取消,并且响应中断。NEW->INTERRUPTING->INTERRUPTED

 

4.核心方法解析

当任务被提交到线程池后,会执行futureTask.run方法。

 

public void run() {        // 校验任务状态
        if (state != NEW || !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;       // double check
            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
            runner = null;
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

 

 

(1)检验当前任务状态是否为NEW以及runner是否已赋值。这一步是防止任务被取消。

(2)double-check任务状态state。

(3)执行业务逻辑,也就是c.call()方法被执行。

(4)如果业务逻辑异常,则调用setException方法将异常对象赋给outcome,并且更新state值。

(5)如果业务正常,则调用set方法将执行结果赋给outcome,并且更新state值。

 

 

protected void set(V v) {
        // state状态 NEW->COMPLETING
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            // COMPLETING -> NORMAL 到达稳定状态
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL);
            // 一些结束工作
            finishCompletion();
        }
    }

 

 

 

 

 

 

protected void setException(Throwable t) {
    // state状态 NEW->COMPLETING
    if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
        outcome = t;
        // COMPLETING -> EXCEPTIONAL 到达稳定状态
        UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL);
        // 一些结束工作
        finishCompletion();
    }
}

 

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

 

 

 

 

 

 

/**
 * 等待任务执行完毕,如果任务取消或者超时则停止
 * @param timed 为true表示设置超时时间
 * @param nanos 超时时间
 * @return 任务完成时的状态
 * @throws InterruptedException
 */
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)
            // 可能任务线程被阻塞了,主线程让出CPU
            Thread.yield();
        else if (q == null)
            // 等待线程节点为空,则初始化新节点并关联当前线程
            q = new WaitNode();
        else if (!queued)
            // 等待线程入队列,成功则queued=true
            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
            // timed=false时会走到这里,挂起当前线程
            LockSupport.park(this);
    }
}


以设置超时时间为例:

 

(1)计算deadline,也就是到某个时间后如果还没有返回结果,那么就超时了。

(2)进入自旋,也就是死循环。

(3)首先判断是否响应线程中断。对于线程中断的响应往往会放在线程进入阻塞之前,这里也印证了这一点。

(4)判断state值,如果>COMPLETING表明任务已经取消或者已经执行完毕,就可以直接返回了。

(5)如果任务还在执行,则为当前线程初始化一个等待节点WaitNode,入等待队列。

(6)计算nanos,判断是否已经超时。如果已经超时,则移除所有等待节点,直接返回state。超时的话,state的值仍然还是COMPLETING。

(7)如果还未超时,就通过LockSupport类提供的方法在指定时间内挂起当前线程,等待任务线程唤醒或者超时唤醒。

 

 

/**
 * 移除并唤醒所有等待线程,执行done,置空callable
 * nulls out callable.
 */
private void finishCompletion() {
    //遍历等待节点
    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;
                // unlink to help gc
                q.next = null;
                q = next;
            }
            break;
        }
    }
    //模板方法,可以被覆盖
    done();
    //清空callable
    callable = null;
}

 

 

 

 

 

这个方法的主要作用是唤醒等待线程。由前文可知,当任务正常结束或者异常时,都会调用finishCompletion去唤醒等待线程。这个时候,等待线程就可以醒了。

 

public boolean cancel(boolean mayInterruptIfRunning) {
        if (state != NEW)
            return false;
        if (mayInterruptIfRunning) {
            if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
                return false;
            Thread t = runner;
            if (t != null)
                t.interrupt();
            UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
        }
        else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
            return false;
        finishCompletion();
        return true;
    }

 

 

 

 

 

(1)state不为NEW时,任务即将进入状态,直接返回false表明取消操作失败。

(2)state状态为NEW,任务可能已经开执行,也可能还未开始。

(3)mayInterruptIfRunning表明是否中断线程,若是,则尝试将state设置为INTERRUPTING,并且中断线程,之后将state设置为终戊INTERRUPTED.

(4)如果mayInterruptIfRunning=false,则不中断线程,把state设置为CANCELLED。

(5)移除等待线程并唤醒。

 

最后欢迎大家访问我的个人网站:1024s

​​​​​​​

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值