Callable/Future 源码分析

本文详细分析了Java中的FutureTask实现原理,包括其内部状态转换、线程同步机制以及get方法的阻塞机制。通过示例代码展示了如何使用FutureTask来获取线程执行结果,并解释了其在并发编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用

public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTask = new FutureTask(new Callable() {
@Override
public Integer call() throws Exception {
Thread.sleep(2000);
return 20;
}
});
new Thread(futureTask).start();
System.out.println(System.currentTimeMillis());
Integer o = (Integer) futureTask.get();
System.out.println(o);
System.out.println(System.currentTimeMillis());
}

Callable/Future 可以阻塞线程,获取线程的返回值

源码分析

继承关系
public interface Runnable {
    public abstract void run();
}
public interface Future<V> {
	//取消
    boolean cancel(boolean mayInterruptIfRunning);
	//是否取消
    boolean isCancelled();
	//是否执行结束
    boolean isDone();
	//获得返回值
    V get() throws InterruptedException, ExecutionException;
	//获得返回值 带超时时间
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
public interface RunnableFuture<V> extends Runnable, Future<V> {
    void run();
}

public class FutureTask<V> implements RunnableFuture<V> {
	//状态 下面的值
	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; // non-volatile, protected by state reads/writes
    //执行线程
    private volatile Thread runner;
    
    private volatile WaitNode waiters;
	//构造方法
	public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }
	
	public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }
	
	//线程启动时执行的方法
	public void run() {
		//如果当前状态不是NEW 或者 设置线程失败,说明有其他线程在执行任务
        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 {
                    result = c.call();//执行call方法,例子中重写的call方法
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)//正常执行完成,设值	
                    set(result);
            }
        } finally {
            runner = null;//清理数据
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }
	//设值方法
	protected void set(V v) {
		//设置状态为 COMPLETING
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;//将返回值设置给成员变量
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // 将状态设置为NORMAL
            finishCompletion();
        }
    }
	//处理
	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;
                    q.next = null; // unlink to help gc
                    q = next;
                }
                break;
            }
        }

        done();

        callable = null;        // to reduce footprint
    }
	
	static final class WaitNode {
        volatile Thread thread;
        volatile WaitNode next;
        WaitNode() { thread = Thread.currentThread(); }
    }
	//get方法
	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;
            }
			//COMPLETING 还未执行完成,让出时间,等待执行完成
            else if (s == COMPLETING) // cannot time out yet
                Thread.yield();
			//初始状态,初始化新的 WaitNode
            else if (q == null)
                q = new WaitNode();
            else if (!queued)//将q设置到队列中
                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);
        }
    }
	//返回值方法  正常执行完成,返回结果,执行异常,报错
	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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值