Callable和Future原理解析

首先进行分析前:我们需要了解到的概念.

Callable是一个接口。是用于创建线程执行里面有一个call方法。用于线程执行的内容,由业务自己定义。

Future也是一个接口。可以异步的通过get方法获取到call返回的内容

比较常见的使用场景:在当前线程中有一个IO操作或者一个比较耗时的操作,而我们又不需要同步、立刻的知道这个操作的值。可以让当前线程去执行别的操作。当需要的时候通过Future的get方法去获取即可.

接下来我们重点分析Fature是如何获取到call的返回值的

@FunctionalInterface
public interface Callable<V> {
    
 //call方法业务自己要执行的内容 其中V是call方法返回的类型,可以是Boolean/Integer 或者其他对象
    V call() throws Exception;
}

public interface Future<V> {

    / 尝试取消此任务的执行。
     * 如果任务已经完成,或者失败或者其他原因无法取消这种尝试将已经被取消,
     * 并且在调用 cancel方法 时此任务尚未启动,
     * 这个任务永远不应该运行。如果任务已经开始,
     * 然后 {@code mayInterruptIfRunning} 参数确定
     * 执行这个任务的线程是否应该被中断
     * 试图停止任务。
    boolean cancel(boolean mayInterruptIfRunning);

    返回true如果这个任务在完成前被取消、  
    boolean isCancelled();

  
    //如果任务已经完成返回true
    boolean isDone();

     // 不带时间的获取返回值
    V get() throws InterruptedException, ExecutionException;

    //带时间的获取返回值
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

接下来我们看一下Callable和fature的用场景r

public class useFatureGetCallableValue{
	public static void main(String[] args) {
		Callable<Boolean > callable = new Callable<Boolean >() {
			public Boolean call() throws Exception {
				//表示执行成功
                return true;
			}
		};
		FutureTask<Boolean> future = new FutureTask<Boolean >(callable);
		new Thread(future).start();
		try {
			Thread.sleep(1000);// 可能做一些事情
			System.out.println(future.get());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
}

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

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

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

    void run();
}


 public void run() {
        // 判断当前线程的执行状态 不是新建或者 当前执行的不是当前线程 。线程执行失败
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            // 构造方法传进来的callable对象
            Callable<V> 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 等待列表
                q = new WaitNode();
            else if (!queued)
                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);
        }
    }

总结下:get的过程、判断当前线程的执行状态,如果已经执行就调用report方法返回当前值 如果还在执行中,那么就等待线程执行完。自旋等待

当线程中断的时候,结束当前线程获取值得操作、并抛出中断异常、

如果线程正在运行中调用thread.yield()方法、让出CPU执行权力,让主线程去执行。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值