Java多线程 - Callable接口解析

1.接口的定义:

public interface Callable<V>   
{   
    V call() throws Exception;   
} 

2.Callable和Runnable的异同

先看下Runnable接口的定义

public interface Runnable {
    public abstract void run();
}

相同点:

1、两者都是接口

2、两者都需要调用Thread.start启动线程

不同点:

1、如上面代码所示,callable的核心是call方法,允许返回值,runnable的核心是run方法,没有返回值

2、call方法可以抛出异常,但是run方法不行

3、因为runnable是java1.1就有了,所以他不存在返回值,后期在java1.5进行了优化,就出现了callable,就有了返回值和抛异常

4、callable和runnable都可以应用于executors。而thread类只支持runnable

3. Callable类型的任务可以有两种执行方式:

我们先定义一个Callable任务MyCallableTask:

class MyCallableTask implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        System.out.println("线程在进行计算");
        Thread.sleep(3000);
        int sum = 0;
        for(int i=0;i<100;i++)
            sum += i;
        return sum;
    }
}

①借助FutureTask执行 
FutureTask类同时实现了两个接口,Future和Runnable接口,所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。

借助FutureTask执行的大体流程是:

Callable<Integer> mycallabletask = new MyCallableTask();  
FutureTask<Integer> futuretask= new FutureTask<Integer>(mycallabletask);  
new Thread(futuretask).start();

通过futuretask可以得到MyCallableTask的call()的运行结果: futuretask.get(); 

②借助线程池来运行 
线程池中执行Callable任务的原型例如:

public interface ExecutorService extends Executor {

  //提交一个Callable任务,返回值为一个Future类型
  <T> Future<T> submit(Callable<T> task);

  //other methods...
  }

借助线程池来运行Callable任务的一般流程为:

  ExecutorService exec = Executors.newCachedThreadPool();
  Future<Integer> future = exec.submit(new MyCallableTask());

4. 底层原理

FutureTask对象实现了Runable接口

看一下它的run方法。

    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 {
                	//拿到结果设置ran为true
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                //异常设置结果为空ran为false并设置异常
                    result = null;
                    ran = false;
                    setException(ex);
                }
                //ran为true时放入结果
                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);
        }
    }
    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        //会一直挂起知道处理业务的线程完成,唤醒等待线程
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }

我们调用get方法时,他先查询线程状态,如果未完成,就调用awaitDone方法。

   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)
                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,到达时间后,会判断线程状态,如果未完成,抛出超时异常。

    public V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException {
        if (unit == null)
            throw new NullPointerException();
        int s = state;
        if (s <= COMPLETING &&
            (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
            throw new TimeoutException();
        return report(s);
    }

因此,带有返回值得异步线程基本上可以这样理解。

由于有返回值,如果未设置等待时间,会等线程执行完成后返回,基本类似同步。其原理是线程运行后,如果未完成,会放入等待队列。直到线程状态变化(完成或者异常等)。如果设置了等待时间,则到时间后无论线程状态是否完成都会返回线程状态。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值