Java并发编程(五)--异步计算

表征异步计算的Future

Future接口有一个get方法,这个方法会执行到计算结束才返回,它可以被中断取消。从它的实现类来看FutureTask来看,其内部也有一个Sync的同步控制类,任务提交的时候会执行

void innerRun() {
            if (!compareAndSetState(0, RUNNING))
                return;
            try {
                runner = Thread.currentThread();
                if (getState() == RUNNING) // recheck after setting thread
                    innerSet(callable.call());
                else
                    releaseShared(0); // cancel
            } catch (Throwable ex) {
                innerSetException(ex);
            }
        }

 

调用innerSet的代码:

 

void innerSet(V v) {
    for (;;) {
int s = getState();
if (s == RAN)
    return;
                if (s == CANCELLED) {
    // aggressively release to set runner to null,
    // in case we are racing with a cancel request
    // that will try to interrupt runner
                    releaseShared(0);
                    return;
                }
if (compareAndSetState(s, RAN)) {
                    result = v;
                    releaseShared(0);
                    done();
    return;
                }
            }
        }

 

一直循环执行,直到完毕后将状态设置为RAN,同时释放锁。

 

用户调用Future.get()方法时,会尝试加锁

V innerGet() throws InterruptedException, ExecutionException {
            acquireSharedInterruptibly(0);
            if (getState() == CANCELLED)
                throw new CancellationException();
            if (exception != null)
                throw new ExecutionException(exception);
            return result;
        }

 

任务执行完毕或者被取消时,释放锁,此时返回result。通过这种方式实现异步计算。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值