/** * runState provides the main lifecyle control, taking on values: * * RUNNING: Accept new tasks and process queued tasks * SHUTDOWN: Don't accept new tasks, but process queued tasks * STOP: Don't accept new tasks, don't process queued tasks, * and interrupt in-progress tasks * TERMINATED: Same as STOP, plus all threads have terminated * * The numerical order among these values matters, to allow * ordered comparisons. The runState monotonically increases over * time, but need not hit each state. The transitions are: * * RUNNING -> SHUTDOWN * On invocation of shutdown(), perhaps implicitly in finalize() * (RUNNING or SHUTDOWN) -> STOP * On invocation of shutdownNow() * SHUTDOWN -> TERMINATED * When both queue and pool are empty * STOP -> TERMINATED * When pool is empty */ volatileint runState; staticfinalintRUNNING=0; staticfinalintSHUTDOWN=1; staticfinalintSTOP=2; staticfinalintTERMINATED=3;
/** * The queue used for holding tasks and handing off to worker * threads. Note that when using this queue, we do not require * that workQueue.poll() returning null necessarily means that * workQueue.isEmpty(), so must sometimes check both. This * accommodates special-purpose queues such as DelayQueues for * which poll() is allowed to return null even if it may later * return non-null when delays expire. * 阻塞队列:用于存放执行的任务。但可能不存储任务, * 仅仅作为线程间通信使用,如:Synchronous */ privatefinal BlockingQueue workQueue;
/** * Lock held on updates to poolSize, corePoolSize, * maximumPoolSize, runState, and workers set. * 全局锁 */ privatefinalReentrantLockmainLock=newReentrantLock();
/** * Wait condition to support awaitTermination */ privatefinalConditiontermination= mainLock.newCondition();
/** * Set containing all worker threads in pool. Accessed only when * holding mainLock. * 存放执行任务的Set */ privatefinalHashSetworkers=newHashSet();
/** * Core pool size, updated only while holding mainLock, but * volatile to allow concurrent readability even during updates. * 核心线程数 */ privatevolatileint corePoolSize;
/** * Maximum pool size, updated only while holding mainLock but * volatile to allow concurrent readability even during updates. * 最大线程数 */ privatevolatileint maximumPoolSize;
/** * Current pool size, updated only while holding mainLock but * volatile to allow concurrent readability even during updates. * 当前线程数 */ privatevolatileint poolSize;
/** * Executes the given task sometime in the future. The task * may execute in a new thread or in an existing pooled thread. * * If the task cannot be submitted for execution, either because this * executor has been shutdown or because its capacity has been reached, * the task is handled by the current RejectedExecutionHandler. * * @param command the task to execute * @throws RejectedExecutionException at discretion of * RejectedExecutionHandler, if task cannot be accepted * for execution * @throws NullPointerException if command is null */ publicvoidexecute(Runnable command) { if (command == null) thrownewNullPointerException(); // 如果当前线程数小于核心线程数,则创建线程并执行该任务 if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) { // 如果当前线程数大于核心线程数,则将该任务插入任务队列等待核心线程执行 if (runState == RUNNING && workQueue.offer(command)) { if (runState != RUNNING || poolSize == 0) ensureQueuedTaskHandled(command); } // 如果当前线程数大于核心数线程数并且该任务插入任务队列失败, // 则将会判断当前线程数是否小于最大线程数,如果小于则创建线程 // 并执行该任务,否则使用饱和(任务)策略执行该任务 elseif (!addIfUnderMaximumPoolSize(command)) reject(command); // is shutdown or saturated } }
/** * Creates and starts a new thread running firstTask as its first * task, only if fewer than corePoolSize threads are running * and the pool is not shut down. * @param firstTask the task the new thread should run first (or * null if none) * @return true if successful * 仅仅当前线程数小于核心线程数并且线程池状态为运行状态时, * 创建一个线程作为核心线程并执行该任务。 */ privatebooleanaddIfUnderCorePoolSize(Runnable firstTask) { Threadt=null; finalReentrantLockmainLock=this.mainLock; mainLock.lock(); try { if (poolSize < corePoolSize && runState == RUNNING) // 创建新线程并执行该任务 t = addThread(firstTask); } finally { mainLock.unlock(); } return t != null; }
/** * Creates and starts a new thread running firstTask as its first * task, only if fewer than maximumPoolSize threads are running * and pool is not shut down. * @param firstTask the task the new thread should run first (or * null if none) * 仅仅当前线程数小于最大线程数并且线程池状态为运行状态时, * 创建一个新线程并执行该任务。 */ privatebooleanaddIfUnderMaximumPoolSize(Runnable firstTask) { Threadt=null; finalReentrantLockmainLock=this.mainLock; mainLock.lock(); try { if (poolSize < maximumPoolSize && runState == RUNNING) // 创建新线程并执行该任务 t = addThread(firstTask); } finally { mainLock.unlock(); } return t != null; }
/** * Creates and returns a new thread running firstTask as its first * task. Call only while holding mainLock. * * @param firstTask the task the new thread should run first (or * null if none) * @return the new thread, or null if threadFactory fails to create thread */ privateThreadaddThread(Runnable firstTask) { Workerw=newWorker(firstTask); // 调用线程工厂创建线线程 Threadt= threadFactory.newThread(w); booleanworkerStarted=false; if (t != null) { if (t.isAlive()) // precheck that t is startable thrownewIllegalThreadStateException(); w.thread = t; workers.add(w); intnt= ++poolSize; if (nt > largestPoolSize) largestPoolSize = nt; try { // 运行该线程执行任务 t.start(); workerStarted = true; } finally { if (!workerStarted) workers.remove(w); } } return t; }
/** * Gets the next task for a worker thread to run. The general * approach is similar to execute() in that worker threads trying * to get a task to run do so on the basis of prevailing state * accessed outside of locks. This may cause them to choose the * "wrong" action, such as trying to exit because no tasks * appear to be available, or entering a take when the pool is in * the process of being shut down. These potential problems are * countered by (1) rechecking pool state (in workerCanExit) * before giving up, and (2) interrupting other workers upon * shutdown, so they can recheck state. All other user-based state * changes (to allowCoreThreadTimeOut etc) are OK even when * performed asynchronously wrt getTask. * * @return the task */ RunnablegetTask() { for (;;) { try { intstate= runState; if (state > SHUTDOWN) returnnull; Runnable r; if (state == SHUTDOWN) // Help drain queue r = workQueue.poll(); // 如果当前线程数大于核心线程数或者允许为核心池线程设置空闲时间 // 将会通过poll(long time,TimeUtile util)方法超时等待任务 elseif (poolSize > corePoolSize || allowCoreThreadTimeOut) r = workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS); // 如果当前线程池数小于或等于核心线程数,该线程就会作为核心线程 // 将会阻塞等待下去,直到任务队列中有任务。 else r = workQueue.take(); if (r != null) return r; if (workerCanExit()) { if (runState >= SHUTDOWN) // Wake up others interruptIdleWorkers(); returnnull; } // Else retry } catch (InterruptedException ie) { // On interruption, re-check runState } } }
publicclassPausableThreadPoolExecutorextendsThreadPoolExecutor { publicPausableThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); }