ThreadPoolExecutor线程池源码解读

来源:互联网 发布:ui设计师必备软件 编辑:程序博客网 时间:2024/06/05 15:51
主要变量:
<span style="font-size:18px;">private volatile int   corePoolSize;private volatile int   maximumPoolSize;private volatile int   poolSize;</span>




构造函数:也就是创建类的时候,需要注入参数。

 public ThreadPoolExecutor(int corePoolSize,                              int maximumPoolSize,                              long keepAliveTime,                              TimeUnit unit,                              BlockingQueue<Runnable> workQueue,                              ThreadFactory threadFactory,                              RejectedExecutionHandler handler) {        if (corePoolSize < 0 ||            maximumPoolSize <= 0 ||            maximumPoolSize < corePoolSize ||            keepAliveTime < 0)            throw new IllegalArgumentException();        if (workQueue == null || threadFactory == null || handler == null)            throw new NullPointerException();        this.corePoolSize = corePoolSize;        this.maximumPoolSize = maximumPoolSize;        this.workQueue = workQueue;        this.keepAliveTime = unit.toNanos(keepAliveTime);        this.threadFactory = threadFactory;        this.handler = handler;    }


执行函数:执行在未来给定任务的某个时候。任务在一个新的线程或在现有池线程可以执行。
 public void execute(Runnable command) {        if (command == null)            throw new NullPointerException();        if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {            if (runState == RUNNING && workQueue.offer(command)) {                if (runState != RUNNING || poolSize == 0)                    ensureQueuedTaskHandled(command);            }            else if (!addIfUnderMaximumPoolSize(command))                reject(command); // is shutdown or saturated        }    }


ensureQueuedTaskHandled()函数:使用了锁机制。

private void ensureQueuedTaskHandled(Runnable command) {        final ReentrantLock mainLock = this.mainLock;        mainLock.lock();        boolean reject = false;        Thread t = null;        try {            int state = runState;            if (state != RUNNING && workQueue.remove(command))                reject = true;            else if (state < STOP &&                     poolSize < Math.max(corePoolSize, 1) &&                     !workQueue.isEmpty())                t = addThread(null);        } finally {            mainLock.unlock();        }        if (reject)            reject(command);        else if (t != null)            t.start();    }




reject 函数
void reject(Runnable command) {        handler.rejectedExecution(command, this);    }





rejectedExecution函数 执行任务中的R呼叫者的线程,如果执行程序已被关闭,在这种情况下,任务被丢弃。

public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {            if (!e.isShutdown()) {                r.run();            }        }



0 0