线程池的理解
ref:这篇博客对源码分析的不错:深入理解java线程池—ThreadPoolExecutor
线程模型
- 1:1 (win,linux的java)
- 1:n
- n:m
线程的状态:
- 新建new
- runable
- blocked
- waitting
- timed_waitting
- teminated
differences betttwen waitting and blocked?
public void run() {
System.out.println("begin");
while (!ss){
// 如果没有获取到o的锁,进入阻塞状态
synchronized (o){
System.out.println("r1run");
// waitting 状态
o.wait();
}
}
System.out.println("finished");
}
java线程池
线程池的状态:
- running
可以添加新的task,同时可以处理队列里面的task
- shutdown
不可以添加新的task,但是可以处理队列里面的task
- stop
不可增加新的task,同时不在处理队列里面的task
- tidying
所有task都空了(可能是主动清空,也可能是自己消耗)
- terminated
结束
状态转化
- running->shutdown
调用shutdown()
- running->stop
调用shuutdownNow()
- shutdown->tidying
shutdown消耗完队列的线程
- stop->tidying
- tidying->terminated
- stop->terminated
代码解释线程池的策略:
代码:首先明确两个概念,worker和task,worker是task运行的容器,task是我们向线程池添加的任务(Runable,Callable,Thread)
package com.dsc;
import java.util.concurrent.*;
public class ThreadPoolTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ThreadPoolExecutor e = new ThreadPoolExecutor(5,10,2000, TimeUnit.SECONDS,new ArrayBlockingQueue<>(10));
for (int i = 0; i < 21; i++) {
e.execute(new Runnable(){
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
while (true) {
}
}
});
System.out.println("getActiveCount:"+e.getActiveCount());
System.out.println("getTaskCount:"+e.getTaskCount());
System.out.println("getCompletedTaskCount:"+e.getCompletedTaskCount());
System.out.printf("------------{%d}----------\n\n",i);
}
Thread.sleep(1000);
System.out.println("fffffffffffffffffffff");
}
}
输出
// step:0-4添加第一worker个进入线程池
// 当线程池池当前task数小于核心池数,根据现有的task作为第一个add(worker),新建一个worker,运行
getActiveCount:1
pool-1-thread-1
getTaskCount:1
getCompletedTaskCount:0
------------{0}----------
getActiveCount:2
getTaskCount:2
getCompletedTaskCount:0
------------{1}----------
getActiveCount:3
getTaskCount:3
getCompletedTaskCount:0
------------{2}----------
pool-1-thread-2
getActiveCount:4
getTaskCount:4
getCompletedTaskCount:0
------------{3}----------
getActiveCount:5
getTaskCount:5
getCompletedTaskCount:0
------------{4}----------
// step5-14 可以看到当前运行task数固定为5个不在改变,因为添加的task直接while在原地了
getActiveCount:5
getTaskCount:6
getCompletedTaskCount:0
------------{5}----------
getActiveCount:5
getTaskCount:7
getCompletedTaskCount:0
------------{6}----------
getActiveCount:5
getTaskCount:8
getCompletedTaskCount:0
------------{7}----------
getActiveCount:5
getTaskCount:9
getCompletedTaskCount:0
------------{8}----------
getActiveCount:5
getTaskCount:10
getCompletedTaskCount:0
------------{9}----------
getActiveCount:5
getTaskCount:11
getCompletedTaskCount:0
------------{10}----------
getActiveCount:5
getTaskCount:12
getCompletedTaskCount:0
------------{11}----------
getActiveCount:5
getTaskCount:13
getCompletedTaskCount:0
------------{12}----------
getActiveCount:5
pool-1-thread-3
getTaskCount:14
getCompletedTaskCount:0
------------{13}----------
getActiveCount:5
getTaskCount:15
getCompletedTaskCount:0
------------{14}----------
// 我们发现这个时候,等待队列的10个空间也被填满了,在这期间,一直没有新的task被运行直到。。。
// 发现当前task的数量增加了,原因是:等待队列不可用(满),则线程池会创建新的worker去处理task,这个时候根据等待队列的特性,取出一个task去运行,因此当前运行线程数ActiveCount为6,
// 接下来的几步中,线程池继续添加task,直到activecount> maxnumpoolsize,此后在添加线程池进入队列,则会执行拒绝策略,step20就是执行了拒绝策略。
getActiveCount:6
getTaskCount:16
getCompletedTaskCount:0
------------{15}----------
getActiveCount:7
getTaskCount:17
getCompletedTaskCount:0
------------{16}----------
getActiveCount:8
getTaskCount:18
getCompletedTaskCount:0
------------{17}----------
getActiveCount:9
getTaskCount:19
getCompletedTaskCount:0
------------{18}----------
getActiveCount:10
getTaskCount:20
getCompletedTaskCount:0
------------{19}----------
// 实际的activeCount>10了,拒绝策略
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task com.dsc.ThreadPoolTest$1@266474c2 rejected from java.util.concurrent.ThreadPoolExecutor@6f94fa3e[Running, pool size = 10, active threads = 10, queued tasks = 10, completed tasks = 0]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
at com.dsc.ThreadPoolTest.main(ThreadPoolTest.java:10)
// 从输出的顺序,我们可以看出,由于采用的是线性的队列(添加的先后顺序),因此是执行的最初的10个线程
pool-1-thread-4
pool-1-thread-5
pool-1-thread-6
pool-1-thread-7
pool-1-thread-8
pool-1-thread-9
pool-1-thread-10
Process finished with exit code 1
再看构造函数
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @param threadFactory the factory to use when the executor
* creates a new thread
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code corePoolSize < 0}<br>
* {@code keepAliveTime < 0}<br>
* {@code maximumPoolSize <= 0}<br>
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue}
* or {@code threadFactory} or {@code handler} is null
*/
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;
}
参数
corePoolSize 核心线程池大小
maximumPoolSize 线程池最大容量大小
keepAliveTime 线程池空闲时,线程存活的时间
TimeUnit 时间单位
ThreadFactory 线程工厂
BlockingQueue任务队列
RejectedExecutionHandler 线程拒绝策略
再来解读一下keepAliveTime,到底是怎么存活,是谁要这样存活。
在gettask()
中找到了keepAliveTime的引用
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
int wc = workerCountOf(c);
// Are workers subject to culling?
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
// 这里,如果timed为真,则不会阻塞队列,否则阻塞,时间过了直接返回null,然后空闲线程调用到null之后就被关闭了,反之,则一直等待,知道又返回位置。timed与默认设置的一个参数allowCoreThreadTimeOut和正在运行的task数也有关。boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
try {
Runnable r = timed ?
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
workQueue.take();
if (r != null)
return r;
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}