Callable和Future原理解析_callable<boolean>

	} catch (ExecutionException e) {
		e.printStackTrace();
	}
}

}


上述代码是一个使用的常见场景,通过FutureTask(实现了RunableAndfature接口)的get方法获取到值、我们看源码如下:



public class FutureTask implements RunnableFuture{

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;  已经被中断

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

}
public interface RunnableFuture extends Runnable, Future {

void run();

}

public void run() {
// 判断当前线程的执行状态 不是新建或者 当前执行的不是当前线程 。线程执行失败
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
// 构造方法传进来的callable对象
Callable c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
// 执行call方法 并获取到返回值result
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
//如果执行成功便set获取到的值 稍后分析
if (ran)
set(result);
}
} finally {

        runner = null;
          // 如果state被中断或者正在被中断。处理中断逻辑 ,
        int s = state;
        if (s >= INTERRUPTING)
            handlePossibleCancellationInterrupt(s);
    }
}


//set 方法
protected void set(V v) {
      cas改变状态值如果成功
    if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
        // 将结果赋值给 outcome 
        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)) {
            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
}

上面我们分析完,执行完fatureTask的run方法成功后,会将结果值存入到outCome中。接下来我们在看看get方法的源码:



public V get() throws InterruptedException, ExecutionException {
    int s = state;
     如果状态还在执行中,那么就等待线程执行完
    if (s <= COMPLETING)
        s = awaitDone(false, 0L);
    return report(s);
}

report中将outcome返回
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)
            //WaitNode 等待列表

最后的话

最近很多小伙伴找我要Linux学习资料,于是我翻箱倒柜,整理了一些优质资源,涵盖视频、电子书、PPT等共享给大家!

资料预览

给大家整理的视频资料:

给大家整理的电子书资料:

如果本文对你有帮助,欢迎点赞、收藏、转发给朋友,让我有持续创作的动力!
资料预览

给大家整理的视频资料:

[外链图片转存中…(img-jdEwkB5Z-1725985373909)]

给大家整理的电子书资料:

[外链图片转存中…(img-kinoZBLY-1725985373909)]

如果本文对你有帮助,欢迎点赞、收藏、转发给朋友,让我有持续创作的动力!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值