FutureTask

FutureTask 实现了Runnable,可由线程池执行run方法。

FutureTask 实现了Future接口,表示一个异步的结果,线程池运行时run方法完成之前,get方法获取结果线程被阻塞,直到run方法执行完成,并设置结果,get线程被唤起,即可获得结果。

 

如果任务处理时间长,可使用线程池的submit方法提交Callable任务,立即返回FutureTask,Callable异步被执行,当前线程可以做其它的事情,再调用FutureTask.get方法获取结果。



 

   FutureTask 使用cas锁原子的设置state变量的状态。

                      state变量表示当前任务的状态。

      需要阻塞线程:调用 LockSupport.park实现。

                     需要唤醒线程:调用 LockSupport.unPark实现。 

  

 public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);//未完成时,阻塞
        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;
            }
            else if (s == COMPLETING) // cannot time out yet
                Thread.yield();//线程放弃cpu时间片,进入可运行状态,下次获取时间片再次运行
            else if (q == null)//为线程创建节点
                q = new WaitNode();
            else if (!queued)
                queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                     q.next = waiters, q);
                //原子的添加到等待链表中 waiters 为等待链表
            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() {
        
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();//执行callable
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);//设置结果
            }
        } finally {
          //ignore code
        }
    }
	
	  protected void set(V v) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {//原子的改变状态为完成
            outcome = v;//设置结果
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            finishCompletion();//完成唤起等待线程
        }
    }
	 private void finishCompletion() {
        // assert state > COMPLETING;
        for (WaitNode q; (q = waiters) != null;) {
            if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {//原子的设置等待链表为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
    }
	
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值