JUC:线程池
1.什么是线程池
可以理解为缓冲区,一组线程得管理工具,如果系统中,频繁得创建销毁线程会带来一定得成本,所以可以预先创建预定数量得线程,由线程池来管理,线程不会立即销毁,以共享得方式为别人提供服务;
链接参考link
2.线程池得实现
ThreadPoolExecutor 实现原理
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue);
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory);
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler);
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler);
- corePoollSize:初始线程数量,核心线程池;
- maxnumPoolSize 最大线程数量,表示线程池中最多能创建多少个线程;
- keepAliveTime :线程池中非核心线程池闲置超时时长(就是没有任务执行得时候,空闲多少时间,就将线程回收了);
- timeUnit:时间单位.上面AliveTime得单位,minute,second 之类…
- workQueue:任务得阻塞队列,线程池中提交得任务runnable,在线程数量达到最大值依旧不能及时处理的时候,会将runnable 提交到队列里面,有各线程轮询获取任务执行.
- ArrayBlockingQueue:基于数组结构得有界阻塞队列,先进先出得**FIFO**原则进行排序.
- LinkedBlockingQueue:结余链表结构得有界阻塞队列
- PriorityBlockingQueue:一个具有优先级的无限阻塞队列
threadFactory:线程得创建工厂,可以进行一些Thread得名字,线程组,优先级之类得设定;
RejectedExecutionHandler: 任务得拒绝策略,当线程数量已经达到了maxnumPoolSize,并且任务队列已经满了,就会拒绝任务;
- AbortPolicy :直接抛出异常
- CallerRunsPolicy: 只用调用者所在线程来运行任务
- DiscardOldestPolicy:丢弃队列里最近的一个任务,来执行此任务
- DiscardPolicy:不处理,直接丢弃掉
ThreadPoolExecutor 源码
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. * * 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. * * 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. */
//分三种情况 (1):当前线程数小于核心线程数,就开启新的线程执行提交得command
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
//(2): 核心线程数不小于corePoolSize,或者开启核心线程失败,就将任务加入到阻塞队列里面,然而我们依然需要检查
//是否需要重新创建Thread? 为啥--> 可能在最后一次检查核心线程的时候,线程died or pool shutdown;
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
//任务队列已经满了导致添加任务失败,就开启非核心线程执行任务
else if (!addWorker(command, false))
reject(command);
}
**addWork()方法**
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
//
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
//当前线程数量 大于了最大系统支持得最大线程数量,或者创建得是非核心线程数量,< maxnumPoolSize
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 {
//创建一个新得线程 worker,woker 里面有个Thread,this.thread = getThreadFactory().newThread(this);
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;
}
**Worker 运行 run**
/** Delegates main run loop to outer runWorker */
public void run() {
runWorker(this);
}
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
Runnable task = w.firstTask;
w.firstTask = null;
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
// 如果worker 里面得task 为空,就到workerQueue里面去获取任务执行
while (task != null || (task = getTask()) != null) {
w.lock();
// If pool is stopping, ensure thread is interrupted;
// if not, ensure thread is not interrupted. This
// requires a recheck in second case to deal with
// shutdownNow race while clearing interrupt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
//线程阻塞
wt.interrupt();
try {
beforeExecute(wt, task);
Throwable thrown = null;
try {
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
afterExecute(task, thrown);
}
} finally {
task = null;
w.completedTasks++;
w.unlock();
}
}
completedAbruptly = false;
} finally {
//当指定任务执行完成,阻塞队列中也取不到可执行任务时,会进入这里,做一些善后工作
//比如在corePoolSize跟maximumPoolSize之间的woker会进行回收
processWorkerExit(w, completedAbruptly);
}
}
使用Executors 创建线程池
//范围:0- Integer.max
ExecutorService executorService = Executors.newCachedThreadPool();
//范围:一个线程
Executors.newSingleThreadExecutor();
//固定线程个数
Executors.newFixedThreadPool(10);
//
Executors.newScheduledThreadPool(12);