【java基础】 callable分析

首先看一个demo

public class App {
    public static void main(String[] args) throws Exception {
        //创建一个Callable的对象
        Callable<Integer> callable = () -> {
            int i=0;
            for(;i<10;i++){
                System.out.println("i++");
                TimeUnit.SECONDS.sleep(1);
            }
            return i;
        };
        通过Callable兑现创建一个FutureTask对象
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        //通过FutureTask对象创建一个线程对象,并启动该线程
        new Thread(futureTask).start();
        //调用FutureTask的get方法
        System.out.println(futureTask.get());
    }
}

有时候面试的时候会问道Callable和Runable的区别

先看下Callbale接口吧,Callable是一个接口,只有一个call方法

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

接着看下FutureTask类,先看下继承关系

该类继承了一个Runable接口,就看下run方法吧,FutureTask有一个Callable的属性,run方法就是执行Callable的call()方法,并将执行的结果赋值给outcome ,并唤醒等待队列中的线程

public void run() {
    if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                    null, Thread.currentThread()))
        return;
    try {
        Callable<V> c = callable;
        if (c != null && state == NEW) {
            V result;
            boolean ran;
            try {
                result = c.call();
                ran = true;
            } catch (Throwable ex) {
                result = null;
                ran = false;
                setException(ex);
            }
            if (ran)
                set(result);
        }
    } finally {
        // runner must be non-null until state is settled to
        // prevent concurrent calls to run()
        runner = null;
        // state must be re-read after nulling runner to prevent
        // leaked interrupts
        int s = state;
        if (s >= INTERRUPTING)
            handlePossibleCancellationInterrupt(s);
    }
}

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 (FutureTask.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);
                }
                FutureTask.WaitNode next = q.next;
                if (next == null)
                    break;
                q.next = null; // unlink to help gc
                q = next;
            }
            break;
        }
    }
    done();
    callable = null;        // to reduce footprint
}

该类继承了一个Future接口,也看下get方法吧

public V get() throws InterruptedException, ExecutionException {
    int s = state;
    if (s <= COMPLETING)
        s = awaitDone(false, 0L);//如果线程状态是NEW,则进入等待状态
    return report(s);
}

private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
    final long deadline = timed ? System.nanoTime() + nanos : 0L;
    FutureTask.WaitNode q = null;
    boolean queued = false;
    /**
     * 死循环,这里要让线程执行足够长的时间
     * 1.第一次进入循环,q为null,执行 q = new FutureTask.WaitNode();
     * 2.第二次进入循环,q不为null,queued=false,执行queued = UNSAFE.compareAndSwapObject(this, waitersOffset,q.next = waiters, q);
     * 3.第三次进入循环,q不为null,queued=true,执行LockSupport.park(this); 该线程(调用get()方法的线程,这里就是主线程)变成WATING状态
     */
    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)
            q = new FutureTask.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);
    }
}


/**
 * 这个方法就是返回之前执行完成之后set的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);
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值