cow-man

Callable接口的设计原理

我们都知道Callable接口作为任务给线程池来执行,可以通过Future对象来获取返回值,他们背后的实现原理是什么?通过总结背后的实现原理有助于我们深入的理解相关技术,做到触类旁通和举一反三。

文章目录

 

一、使用示例

先通过一个简单示例来了解Callable如何使用:

 

public class FutureTaskTest {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        Task task = new Task();
        Future<Integer> result = executor.submit(task);
        executor.shutdown();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        System.out.println("主线程在执行任务");

        try {
            System.out.println("task运行结果"+result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        System.out.println("所有任务执行完毕");
    }

    static class Task implements Callable<Integer> {

        public Integer call() throws Exception {
            System.out.println("子线程在进行计算");
            Thread.sleep(30000);
            int sum = 0;
            for(int i=0;i<100;i++)
                sum += i;
            return sum;
        }
    }

}

  

 

 

二、工作流程分析

通过调试代码可知Callable工作流程如下:
1.submit方法接受Callable接口,首先包裹成功FutureTask对象,并作为返回值返回。
2.调用ThreadPoolExecutor.execute方法
2.1 线程池中的工作线程最终执行后会调用FutureTask的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 {
                    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);
        }
    }

2.2 run方法主要是执行Callable接口,并把返回值写入到FutureTask的outcome属性中,并调用LockSupport.unpack方法
3.主线程继续执行。
4.主线程调用FutureTask.get方法获取返回值。
4.1 如果FutureTask计算没有完成,那么需要等待完成,这个时候会调用LockSupport.pack方法阻塞线程

    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);
        }
    }

 

 

三、工作流程归纳

Callable工作流程归纳:
1.submit方法接受Callable接口,首先包裹成功futruetask对象,并作为返回值返回。
2.FutureTask实现了Runnable接口和Future接口。由于实现了Runnable接口(runnable实现方法中会调用Callable接口),可以给线程池执行;future接口管理执行过程,比方说取消,阻塞获取执行结果,判断是否执行完成,是否取消。

所以Callable接口实现的核心是FutureTask,所以FutureTask提供了哪些功能呢?

四、FutureTask需求要点

FutureTask需求要点:

1.依赖一个Callable接口,这个接口表示具体需要执行的任务。
2.必须是一个Task,也就是说能够交给线程池执行。
3.能够同步获取执行结果。
4.支持取消。

五、FutureTask设计思路

FutureTask设计思路,这里为了简单起见,实现前面三个需求,并且只考虑一个任务的场景:
1.通过构造器注入Callable接口
2.Task需要给线程池执行,所以必须实现runnable接口,实现方法中需要调用Callable接口来执行任务
3.同步获取执行结果的方法中如果任务没有执行完成需要阻塞同步线程,等待task线程执行完后需要唤醒阻塞线程,主线程继续执行就能拿到执行结果了。

 

posted on 2018-08-09 23:46  cow-man  阅读(155)  评论(0)    收藏  举报

导航