线程池ThreadPoolExecutor

ThreadPoolExecutor


Executor、ExecutorService是两个规范了一系列方法的接口
AbstractExecutorService实现了submit()、invoke()相关的一些方法

AbstractExecutorService

我们先来看看我们经常使用的submit吧

public Future<?> submit(Runnable task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<Void> ftask = newTaskFor(task, null);
        execute(ftask);
        return ftask;
    }

在方法的第二行,使用了newTask()方法,我们来看看

protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
        return new FutureTask<T>(runnable, value);
    }

传入我们要执行的任务,返回了一个FutureTask对象,我们会发现,线程池的内部工作和FutureTask息息相关,我们先来看看FutureTask是什么吧

FutureTask

继承关系

在这里插入图片描述
Future和Runnable是提交线程任务的两种模式,RunnableFuture有一个Run()方法,接下来我们看看FutureTask内部结构到底是什么

成员变量
    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;
    private volatile Thread runner;
    private volatile WaitNode waiters;
    private static final sun.misc.Unsafe UNSAFE;
    private static final long stateOffset;
    private static final long runnerOffset;
    private static final long waitersOffset;

state是表示当前任务的执行状态,包含了下面的6个状态值,最初创建时是NEW,COMPLETING表示正在执行该任务,NORMAL表示该任务正常执行完成,EXCEPTIONAL表示该任务执行结束但是出现异常情况,CANCELLED 表示该任务被取消,INTERRUPTING、 INTERRUPTED表示该任务被中断中和已经被中断
callable是提交进来的任务,记得刚刚提交用的参数不是Runnable吗,怎么到这儿变成了Callable,好的,我们来看看是为什么

public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

Executors.callable(runnable, result);将Runnable变成了Callable,是不是让你想起了适配器模式?我们来看看

public static <T> Callable<T> callable(Runnable task, T result) {
        if (task == null)
            throw new NullPointerException();
        return new RunnableAdapter<T>(task, result);
    }
    static final class RunnableAdapter<T> implements Callable<T> {
        final Runnable task;
        final T result;
        RunnableAdapter(Runnable task, T result) {
            this.task = task;
            this.result = result;
        }
        public T call() {
            task.run();
            return result;
        }
    }

回到刚刚的位置,outcome变量是执行任务的结果,有可能是你想要的结果,也有可能是异常信息……
runner是执行任务的线程
waiters是一个记录等待线程的链表结构变量

static final class WaitNode {
        volatile Thread thread;
        volatile WaitNode next;
        WaitNode() { thread = Thread.currentThread(); }
    }

剩下的四个变量是用来记录state、runner、waiters的内存位置以及直接操作内存改变这三个变量值

具体方法
获取任务执行结果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;
            }
            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);
        }
    }
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);
    }

执行get()方法时,如果任务状态是NEW,当前线程将会被阻塞,等待完成后调用finishCompletio()唤醒线程;如果是COMPLETING将会让出cpu执行单元片,等待执行完成返回结果。

任务执行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);
        }
    }

流程就是初始化执行线程runner、执行任务call()、如果成功执行给outCome结果集否则就是异常值,如果中途被中断了,在finnaly里面还要让出cpu时间片直到中断完成


FutureTask大概就是这样,我们来看AbstractExecutorService的submit方法,它最后是使用了execute方法来执行futureTask任务,该方法是在ThreadPoolExecutor中实现(ps:这儿算是使用了一个模板方法的设计模式)
聊完了submit我们再来看一看剩下的相关的invoke方法吧

public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
        throws InterruptedException {
        if (tasks == null)
            throw new NullPointerException();
        ArrayList<Future<T>> futures = new ArrayList<Future<T>>(tasks.size());
        boolean done = false;
        try {
            for (Callable<T> t : tasks) {
                RunnableFuture<T> f = newTaskFor(t);
                futures.add(f);
                execute(f);
            }
            for (int i = 0, size = futures.size(); i < size; i++) {
                Future<T> f = futures.get(i);
                if (!f.isDone()) {
                    try {
                        f.get();
                    } catch (CancellationException ignore) {
                    } catch (ExecutionException ignore) {
                    }
                }
            }
            done = true;
            return futures;
        } finally {
            if (!done)
                for (int i = 0, size = futures.size(); i < size; i++)
                    futures.get(i).cancel(true);
        }
    }

首先给所有传入的Runnable任务创建RunnableTask,然后一一执行,直到所有都执行结束然后返回。
而invokeAny()等方法是只要有一个执行完成,就返回结果集。


以上就是ThreadPoolExecutor的实现上层,我们接下来看看我们使用的线程池吧

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值