线程池

线程池的根本运用

package com.shothook.test;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Slf4j
public class ThreadPoolDemo {
public static void main(String[] args) {
ExecutorService threadPool = new ThreadPoolExecutor(10, 1000, 10, TimeUnit.SECONDS,  new LinkedBlockingDeque<>(10));
LocalDateTime start = LocalDateTime.now();
for (int i = 0; i < 1000; i++) {
threadPool.submit(new Task(i));
}
LocalDateTime end = LocalDateTime.now();
Duration duration = Duration.between(start,end);
log.debug("submit task complete, takes time: {}", duration.getNano());
}
@AllArgsConstructor
@Slf4j
public static class Task implements Runnable {
private int i;
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("thread name: {}, to execute task: {}", Thread.currentThread().getName(), i);
}
}
}

线程池的作业形式,简略来说如下所示:

主线程往缓冲行列中增加使命,线程池从行列中取使命并履行,当然,真实情况比这杂乱的多,这个后边再详细分析,先有个概念就好。

创立线程池的各个参数的含义

线程池的结构函数:线程池

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.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}

corePoolSize:中心线程数
maximumPoolSize:最大线程数,当往缓冲行列中增加使命,缓冲行列满时,会在corePoolSize的基础上持续新建线程,知道触发最大线程数
keepAliveTime:超越中心线程数的线程的存活时间,对超越存活时间的,线程池结束超时的闲暇线程
unit:超越中心线程数的线程的存活时间对应的时间单位
workQueue:线程池的使命缓存行列
threadFactory:创立线程的工厂
handler:当到最大线程数,而且缓存行列满时,持续增加使命时的处理战略

线程池的状况

    private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
private static final int COUNT_BITS = Integer.SIZE - 3;
private static final int CAPACITY   = (1 << COUNT_BITS) - 1;
private static final int RUNNING    = -1 << COUNT_BITS;
private static final int SHUTDOWN   =  0 << COUNT_BITS;
private static final int STOP       =  1 << COUNT_BITS;
private static final int TIDYING    =  2 << COUNT_BITS;
private static final int TERMINATED =  3 << COUNT_BITS;
private static int runStateOf(int c)     { return c & ~CAPACITY; }//获取线程池的状况
private static int workerCountOf(int c)  { return c & CAPACITY; }//获取线程池的线程数
private static int ctlOf(int rs, int wc) { return rs | wc; }//参数rs表明runState,参数wc表明workerCount,即依据runState和workerCount打包合并成ctl

ctl : 高三位保存线程池状况,低29位保存使命数。

线程池的创立

/**
* 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 {@code RejectedExecutionHandler}.
* 假如使命无法被提交履行,要么是由于这个Executor现已被shutdown封闭,要么是现已到达其容量上限,使命会被当时的RejectedExecutionHandler处理
*
* @param command the task to execute
* @throws RejectedExecutionException at discretion of
*         {@code RejectedExecutionHandler}, if the task
*         cannot be accepted for execution                 RejectedExecutionException是一个RuntimeException
* @throws NullPointerException if {@code command} is null
*/
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task.  The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
* 假如运转的线程少于corePoolSize,测验敞开一个新线程去运转command,command作为这个线程的第一个使命
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
* 假如使命成功放入行列,咱们仍需求一个两层校验去承认是否应该新建一个线程(由于或许存在有些线程在咱们前次查看后死了) 或许 从咱们进入这个办法后,pool被封闭了
* 所以咱们需求再次查看state,假如线程池中止了需求回滚入行列,假如池中没有线程了,新敞开 一个线程
*
* 3. If we cannot queue task, then we try to add a new
* thread.  If it fails, we know we are shut down or saturated
* and so reject the task.
* 假如无法将使命入行列(或许行列满了),需求新开区一个线程(自己:往maxPoolSize开展)
* 假如失利了,阐明线程池shutdown 或许 饱和了,所以咱们回绝使命
*/
int c = ctl.get();
/**
* 1、假如当时线程数少于corePoolSize(或许是由于addWorker()操作现已包括对线程池状况的判别,如此处没加,而入workQueue前加了)
*/
if (workerCountOf(c) < corePoolSize) {
//addWorker()成功,回来
if (addWorker(command, true))
return;
/**
* 没有成功addWorker(),再次获取c(但凡需求再次用ctl做判别时,都会再次调用ctl.get())
* 失利的原因或许是:
* 1、线程池现已shutdown,shutdown的线程池不再接纳新使命
* 2、workerCountOf(c) < corePoolSize 判别后,由于并发,其他线程先创立了worker线程,导致workerCount>=corePoolSize
*/
c = ctl.get();
}
/**
* 2、假如线程池RUNNING状况,且入行列成功
*/
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();//再次校验位
/**
* 再次校验放入workerQueue中的使命是否能被履行
* 1、假如线程池不是运转状况了,应该回绝增加新使命,从workQueue中删去使命
* 2、假如线程池是运转状况,或许从workQueue中删去使命失利(刚好有一个线程履行结束,并耗费了这个使命),确保还有线程履行使命(只需有一个就够了)
*/
//假如再次校验过程中,线程池不是RUNNING状况,而且remove(command)--workQueue.remove()成功,回绝当时command
if (! isRunning(recheck) && remove(command))
reject(command);
//假如当时worker数量为0,经过addWorker(null, false)创立一个线程,其使命为null
//为什么只查看运转的worker数量是不是0呢?? 为什么不好corePoolSize比较呢??
//只确保有一个worker线程能够从queue中获取使命履行就行了??
//由于只需还有活动的worker线程,就能够消费workerQueue中的使命
else if (workerCountOf(recheck) == 0)
addWorker(null, false);  //第一个参数为null,阐明只为新建一个worker线程,没有指定firstTask
//第二个参数为true代表占用corePoolSize,false占用maxPoolSize
}
/**
* 3、假如线程池不是running状况 或许 无法入行列
*   测验敞开新线程,扩容至maxPoolSize,假如addWork(command, false)失利了,回绝当时command
*/
else if (!addWorker(command, false))
reject(command);
}

新建线程

private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);//线程池状况
// Check if queue empty only if necessary.
// 线程池为SHUTDOWN状况,当时创立新线程的使命为空,而且线程池的行列不为空
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get();  // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
boolean workerStarted = false;
boolean workerAdded = false;
Worker w = null;
try {
w = new Worker(firstTask);
final Thread t = w.thread;
if (t != null) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// Recheck while holding lock.
// Back out on ThreadFactory failure or if
// shut down before lock acquired.
int rs = runStateOf(ctl.get());
if (rs < SHUTDOWN ||
(rs == SHUTDOWN && firstTask == null)) {
if (t.isAlive()) // precheck that t is startable
throw new IllegalThreadStateException();
workers.add(w);
int s = workers.size();
if (s > largestPoolSize)
largestPoolSize = s;
workerAdded = true;
}
} finally {
mainLock.unlock();
}
if (workerAdded) {
t.start();
workerStarted = true;
}
}
} finally {
if (! workerStarted)
addWorkerFailed(w);
}
return workerStarted;
}

钩子

    protected void beforeExecute(Thread t, Runnable r) { }
protected void afterExecute(Runnable r, Throwable t) { }

线程池的类图