1、自定义线程池
线程是一种系统资源,每创建一次,都会耗费一定的系统资源,如果是在高并发的场景下,每次任务都创建一个新的线程,那么这样对系统占用是相当大的,甚至会产生内存溢出的问题,而且线程存在的数量也不能太多,如果太多,频繁的上下文切换,也会有很大的负担,处于这两个原因,我们可以充分利用已有的线程,而不是每次创建新的线程
首先是阻塞队列
@Slf4j
class BlockingQueue<T> {
/**
* 默认阻塞任务队列大小
*/
private static final Integer DEFAULT_QUEUE_CAPACITY = 5;
/**
* 阻塞队列
*/
private Queue<T> queue;
/**
* 阻塞队列可能会有多个线程操作,需要保证线程安全,所以需要用到锁
*/
private final ReentrantLock lock = new ReentrantLock();
/**
* 如果队列已经满了,那么不能再往里添加任务了,添加任务的线程需要阻塞住
*/
private final Condition putWaitSet = lock.newCondition();
/**
* 如果队列已经是空了,那么不能再取任务了,取任务的线程就需要阻塞住
*/
private final Condition getWaitSet = lock.newCondition();
/**
* 阻塞任务队列容量
*/
private final int capacity;
/**
* 无参构造
*/
public BlockingQueue() {
this.capacity = DEFAULT_QUEUE_CAPACITY;
initQueue();
}
/**
* 携带初始容量的有参构造
*
* @param capacity 自定义容量大小
*/
public BlockingQueue(int capacity) {
this.capacity = capacity;
initQueue();
}
/**
* 创建任务队列
*/
private void initQueue() {
queue = new ArrayDeque<>(this.capacity);
}
/**
* 阻塞获取任务,且不带超时时间
*
* @return T 任务对象
*/
public T get() {
lock.lock();
try {
while (queue.size() == 0) {
try {
getWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T t = queue.poll();
putWaitSet.signalAll();
return t;
} finally {
lock.unlock();
}
}
/**
* 阻塞获取任务,且带超时时间
*
* @param timeout 超时时间
* @param timeUnit 超时时间单位
* @return T 任务对象
*/
public T get(long timeout, TimeUnit timeUnit) {
lock.lock();
try {
long nanosTime = timeUnit.toNanos(timeout);
while (queue.size() == 0) {
try {
if (nanosTime <= 0) {
return null;
}
nanosTime = getWaitSet.awaitNanos(nanosTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T t = queue.poll();
putWaitSet.signalAll();
return t;
} finally {
lock.unlock();
}
}
/**
* 阻塞添加任务
*
* @param t 任务对象
*/
public void put(T t) {
lock.lock();
try {
while (queue.size() == capacity) {
try {
log.info("任务:{} 等待加入阻塞任务队列", t);
putWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.add(t);
getWaitSet.signalAll();
log.info("任务:{} 加入阻塞任务队列", t);
} finally {
lock.unlock();
}
}
/**
* 获取任务队列大小
*
* @return int 任务队列大小
*/
public int size() {
lock.lock();
try {
return queue.size();
} finally {
lock.unlock();
}
}
}
然后是自定义线程池
@Slf4j
class ThreadPool {
/**
* 阻塞的任务队列
*/
private final BlockingQueue<Runnable> blockingQueue;
/**
* 工作线程
*/
private final Set<Worker> workers;
/**
* 默认的工作线程数量
*/
private static final int DEFAULT_POOL_SIZE = 5;
/**
* 默认的阻塞任务队列任务数量
*/
private static final int DEFAULT_QUEUE_SIZE = 5;
/**
* 默认的等待时间单位
*/
private static final TimeUnit DEFAULT_TIME_UNIT = TimeUnit.SECONDS;
/**
* 默认的阻塞等待时间
*/
private static final int DEFAULT_TIMEOUT = 5;
/**
* 工作线程数
*/
private final int poolSize;
/**
* 任务队列任务最大数
*/
private final int queueSize;
/**
* 等待时间单位
*/
private final TimeUnit timeUnit;
/**
* 阻塞等待时间
*/
private final int timeout;
/**
* 无参构造
*/
public ThreadPool() {
poolSize = DEFAULT_POOL_SIZE;
queueSize = DEFAULT_QUEUE_SIZE;
timeUnit = DEFAULT_TIME_UNIT;
timeout = DEFAULT_TIMEOUT;
blockingQueue = new BlockingQueue<>(queueSize);
workers = new HashSet<>(poolSize);
}
/**
* 带参构造
*
* @param queueSize 阻塞任务队列任务最大数
* @param poolSize 工作线程数
*/
public ThreadPool(int queueSize, int poolSize, TimeUnit timeUnit, int timeout) {
this.poolSize = poolSize;
this.queueSize = queueSize;
this.timeUnit = timeUnit;
this.timeout = timeout;
this.blockingQueue = new BlockingQueue<>(queueSize);
this.workers = new HashSet<>(poolSize);
}
/**
* 执行一个任务
*
* @param task 任务对象
*/
public void execute(Runnable task) {
synchronized (workers) {
if (workers.size() < poolSize) {
Worker worker = new Worker(task);
log.info("创建新的任务工作线程: {} ,执行任务:{}", worker, task);
workers.add(worker);
worker.start();
} else {
blockingQueue.put(task);
}
}
}
/**
* 工作线程的包装类
*/
@Data
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
@AllArgsConstructor
class Worker extends Thread {
private Runnable task;
@Override
public void run() {
while (task != null || (task = blockingQueue.get(timeout, timeUnit)) != null) {
try {
log.info("正在执行:{}", task);
task.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
task = null;
}
}
synchronized (workers) {
log.info("工作线程被移除:{}", this);
workers.remove(this);
}
}
}
}
测试
@Slf4j
public class TestPool {
public static void main(String[] args) {
ThreadPool pool = new ThreadPool(10, 2, TimeUnit.SECONDS, 2);
for (int i = 0; i < 15; i++) {
int j = i;
pool.execute(() -> {
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info(String.valueOf(j));
});
}
}
}
[main] INFO com.phz.juc.ThreadPool - 创建新的任务工作线程: ThreadPool.Worker(task=com.phz.juc.TestPool$$Lambda$2/1225358173@76fb509a) ,执行任务:com.phz.juc.TestPool$$Lambda$2/1225358173@76fb509a
[main] INFO com.phz.juc.ThreadPool - 创建新的任务工作线程: ThreadPool.Worker(task=com.phz.juc.TestPool$$Lambda$2/1225358173@2e817b38) ,执行任务:com.phz.juc.TestPool$$Lambda$2/1225358173@2e817b38
[main] INFO com.phz.juc.BlockingQueue - 任务:com.phz.juc.TestPool$$Lambda$2/1225358173@c4437c4 加入阻塞任务队列
[Thread-0] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$2/1225358173@76fb509a
[main] INFO com.phz.juc.BlockingQueue - 任务:com.phz.juc.TestPool$$Lambda$2/1225358173@433c675d 加入阻塞任务队列
[Thread-1] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$2/1225358173@2e817b38
[main] INFO com.phz.juc.BlockingQueue - 任务:com.phz.juc.TestPool$$Lambda$2/1225358173@3f91beef 加入阻塞任务队列
[main] INFO com.phz.juc.BlockingQueue - 任务:com.phz.juc.TestPool$$Lambda$2/1225358173@1a6c5a9e 加入阻塞任务队列
[main] INFO com.phz.juc.BlockingQueue - 任务:com.phz.juc.TestPool$$Lambda$2/1225358173@37bba400 加入阻塞任务队列
[main] INFO com.phz.juc.BlockingQueue - 任务:com.phz.juc.TestPool$$Lambda$2/1225358173@179d3b25 加入阻塞任务队列
[main] INFO com.phz.juc.BlockingQueue - 任务:com.phz.juc.TestPool$$Lambda$2/1225358173@254989ff 加入阻塞任务队列
[main] INFO com.phz.juc.BlockingQueue - 任务:com.phz.juc.TestPool$$Lambda$2/1225358173@5d099f62 加入阻塞任务队列
[main] INFO com.phz.juc.BlockingQueue - 任务:com.phz.juc.TestPool$$Lambda$2/1225358173@37f8bb67 加入阻塞任务队列
[main] INFO com.phz.juc.BlockingQueue - 任务:com.phz.juc.TestPool$$Lambda$2/1225358173@49c2faae 加入阻塞任务队列
[main] INFO com.phz.juc.BlockingQueue - 任务:com.phz.juc.TestPool$$Lambda$2/1225358173@20ad9418 等待加入阻塞任务队列
[Thread-0] INFO com.phz.juc.TestPool - 0
[Thread-1] INFO com.phz.juc.TestPool - 1
[Thread-0] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$2/1225358173@c4437c4
[main] INFO com.phz.juc.BlockingQueue - 任务:com.phz.juc.TestPool$$Lambda$2/1225358173@20ad9418 加入阻塞任务队列
[main] INFO com.phz.juc.BlockingQueue - 任务:com.phz.juc.TestPool$$Lambda$2/1225358173@439f5b3d 等待加入阻塞任务队列
[Thread-1] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$2/1225358173@433c675d
[main] INFO com.phz.juc.BlockingQueue - 任务:com.phz.juc.TestPool$$Lambda$2/1225358173@439f5b3d 加入阻塞任务队列
[main] INFO com.phz.juc.BlockingQueue - 任务:com.phz.juc.TestPool$$Lambda$2/1225358173@1d56ce6a 等待加入阻塞任务队列
[Thread-1] INFO com.phz.juc.TestPool - 3
[Thread-0] INFO com.phz.juc.TestPool - 2
[Thread-1] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$2/1225358173@3f91beef
[Thread-0] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$2/1225358173@1a6c5a9e
[main] INFO com.phz.juc.BlockingQueue - 任务:com.phz.juc.TestPool$$Lambda$2/1225358173@1d56ce6a 加入阻塞任务队列
[Thread-1] INFO com.phz.juc.TestPool - 4
[Thread-0] INFO com.phz.juc.TestPool - 5
[Thread-1] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$2/1225358173@37bba400
[Thread-0] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$2/1225358173@179d3b25
[Thread-1] INFO com.phz.juc.TestPool - 6
[Thread-0] INFO com.phz.juc.TestPool - 7
[Thread-1] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$2/1225358173@254989ff
[Thread-0] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$2/1225358173@5d099f62
[Thread-0] INFO com.phz.juc.TestPool - 9
[Thread-1] INFO com.phz.juc.TestPool - 8
[Thread-0] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$2/1225358173@37f8bb67
[Thread-1] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$2/1225358173@49c2faae
[Thread-0] INFO com.phz.juc.TestPool - 10
[Thread-1] INFO com.phz.juc.TestPool - 11
[Thread-0] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$2/1225358173@20ad9418
[Thread-1] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$2/1225358173@439f5b3d
[Thread-0] INFO com.phz.juc.TestPool - 12
[Thread-1] INFO com.phz.juc.TestPool - 13
[Thread-0] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$2/1225358173@1d56ce6a
[Thread-1] INFO com.phz.juc.ThreadPool - 工作线程被移除:ThreadPool.Worker(task=null)
[Thread-0] INFO com.phz.juc.TestPool - 14
[Thread-0] INFO com.phz.juc.ThreadPool - 工作线程被移除:ThreadPool.Worker(task=null)
2、拒绝策略
如果要执行的任务耗时较长,那么会出现什么情况呢?
@Slf4j
public class TestPool {
public static void main(String[] args) {
ThreadPool pool = new ThreadPool(10, 2, TimeUnit.SECONDS, 2);
for (int i = 0; i < 20; i++) {
int j = i;
pool.execute(() -> {
try {
TimeUnit.SECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info(String.valueOf(j));
});
}
}
}
可以看到主线程就一直死等在这里,无法继续执行后续任务了,对于这种情况我们是不是应该抛出异常或者拒绝执行来优化呢,又或者就是要死等,又或者是让调用者自己执行任务…这么多可能性,如果应用到代码中,大概是会有特别多的 if 分支吧,这个时候我们就可以采用策略模式,来归纳所有的拒绝策略
@FunctionalInterface
interface RejectPolicy<T> {
/**
* 拒绝策略方法
*
* @param queue 阻塞队列
* @param task 任务对象
*/
void reject(ArrayDeque<T> queue, T task);
}
ThreadPool 做对应修改
@Slf4j
class ThreadPool {
/**
* 阻塞的任务队列
*/
private final BlockingQueue<Runnable> blockingQueue;
/**
* 工作线程
*/
private final Set<Worker> workers;
/**
* 默认的工作线程数量
*/
private static final int DEFAULT_POOL_SIZE = 5;
/**
* 默认的阻塞任务队列任务数量
*/
private static final int DEFAULT_QUEUE_SIZE = 5;
/**
* 默认的等待时间单位
*/
private static final TimeUnit DEFAULT_TIME_UNIT = TimeUnit.SECONDS;
/**
* 默认的阻塞等待时间
*/
private static final int DEFAULT_TIMEOUT = 5;
/**
* 工作线程数
*/
private final int poolSize;
/**
* 任务队列任务最大数
*/
private final int queueSize;
/**
* 等待时间单位
*/
private final TimeUnit timeUnit;
/**
* 阻塞等待时间
*/
private final int timeout;
/**
* 拒绝策略
*/
private final RejectPolicy<Runnable> rejectPolicy;
/**
* 无参构造
*/
public ThreadPool() {
poolSize = DEFAULT_POOL_SIZE;
queueSize = DEFAULT_QUEUE_SIZE;
timeUnit = DEFAULT_TIME_UNIT;
timeout = DEFAULT_TIMEOUT;
blockingQueue = new BlockingQueue<>(queueSize);
workers = new HashSet<>(poolSize);
//默认调用线程自己执行
rejectPolicy = (queue, task) -> task.run();
}
/**
* 带参构造
*
* @param queueSize 阻塞任务队列任务最大数
* @param poolSize 工作线程数
*/
public ThreadPool(int queueSize, int poolSize, TimeUnit timeUnit, int timeout, RejectPolicy<Runnable> rejectPolicy) {
this.poolSize = poolSize;
this.queueSize = queueSize;
this.timeUnit = timeUnit;
this.timeout = timeout;
this.blockingQueue = new BlockingQueue<>(queueSize);
this.workers = new HashSet<>(poolSize);
this.rejectPolicy = rejectPolicy;
}
/**
* 执行一个任务
*
* @param task 任务对象
*/
public void execute(Runnable task) {
synchronized (workers) {
if (workers.size() < poolSize) {
Worker worker = new Worker(task);
log.info("创建新的任务工作线程: {} ,执行任务:{}", worker, task);
workers.add(worker);
worker.start();
} else {
blockingQueue.tryPut(rejectPolicy, task);
}
}
}
/**
* 工作线程的包装类
*/
@Data
@EqualsAndHashCode(callSuper = false)
@NoArgsConstructor
@AllArgsConstructor
class Worker extends Thread {
private Runnable task;
@Override
public void run() {
while (task != null || (task = blockingQueue.get(timeout, timeUnit)) != null) {
try {
log.info("正在执行:{}", task);
task.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
task = null;
}
}
synchronized (workers) {
log.info("工作线程被移除:{}", this);
workers.remove(this);
}
}
}
}
阻塞队列也需要修改
@Slf4j
class BlockingQueue<T> {
/**
* 默认阻塞任务队列大小
*/
private static final Integer DEFAULT_QUEUE_CAPACITY = 5;
/**
* 阻塞队列
*/
private ArrayDeque<T> queue;
/**
* 阻塞队列可能会有多个线程操作,需要保证线程安全,所以需要用到锁
*/
private final ReentrantLock lock = new ReentrantLock();
/**
* 如果队列已经满了,那么不能再往里添加任务了,添加任务的线程需要阻塞住
*/
private final Condition putWaitSet = lock.newCondition();
/**
* 如果队列已经是空了,那么不能再取任务了,取任务的线程就需要阻塞住
*/
private final Condition getWaitSet = lock.newCondition();
/**
* 阻塞任务队列容量
*/
private final int capacity;
/**
* 无参构造
*/
public BlockingQueue() {
this.capacity = DEFAULT_QUEUE_CAPACITY;
initQueue();
}
/**
* 携带初始容量的有参构造
*
* @param capacity 自定义容量大小
*/
public BlockingQueue(int capacity) {
this.capacity = capacity;
initQueue();
}
/**
* 创建任务队列
*/
private void initQueue() {
queue = new ArrayDeque<>(this.capacity);
}
/**
* 阻塞获取任务,且不带超时时间
*
* @return T 任务对象
*/
public T get() {
lock.lock();
try {
while (queue.size() == 0) {
try {
getWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T t = queue.poll();
putWaitSet.signalAll();
return t;
} finally {
lock.unlock();
}
}
/**
* 阻塞获取任务,且带超时时间
*
* @param timeout 超时时间
* @param timeUnit 超时时间单位
* @return T 任务对象
*/
public T get(long timeout, TimeUnit timeUnit) {
lock.lock();
try {
long nanosTime = timeUnit.toNanos(timeout);
while (queue.size() == 0) {
try {
if (nanosTime <= 0) {
return null;
}
nanosTime = getWaitSet.awaitNanos(nanosTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T t = queue.poll();
putWaitSet.signalAll();
return t;
} finally {
lock.unlock();
}
}
/**
* 阻塞添加任务
*
* @param t 任务对象
*/
public void put(T t) {
lock.lock();
try {
while (queue.size() == capacity) {
try {
log.info("任务:{} 等待加入阻塞任务队列", t);
putWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.add(t);
getWaitSet.signalAll();
log.info("任务:{} 加入阻塞任务队列", t);
} finally {
lock.unlock();
}
}
/**
* 携带超时时间阻塞添加任务
*
* @param t 任务对象
* @param timeout 超时时长
* @param timeUnit 超时时长单位
*/
public boolean put(T t, long timeout, TimeUnit timeUnit) {
lock.lock();
try {
long nanos = timeUnit.toNanos(timeout);
while (queue.size() == capacity) {
try {
if (nanos <= 0) {
log.info("加入任务超时,取消添加");
return false;
}
log.info("任务:{} 等待加入阻塞任务队列", t);
nanos = putWaitSet.awaitNanos(nanos);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.add(t);
getWaitSet.signalAll();
log.info("任务:{} 加入阻塞任务队列", t);
return true;
} finally {
lock.unlock();
}
}
/**
* 获取任务队列大小
*
* @return int 任务队列大小
*/
public int size() {
lock.lock();
try {
return queue.size();
} finally {
lock.unlock();
}
}
/**
* 携带拒绝策略的添加任务
*
* @param rejectPolicy 拒绝策略
* @param task 任务对象
*/
public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
lock.lock();
try {
if (queue.size() == capacity) {
rejectPolicy.reject(queue, task);
} else {
log.info("加入任务队列: {}", task);
queue.add(task);
getWaitSet.signalAll();
}
} finally {
lock.unlock();
}
}
}
测试
ThreadPool pool = new ThreadPool(10, 2, TimeUnit.SECONDS, 2,
//放弃执行
(blockingQueue, task) -> {
log.info("放弃{}", task);
}
);
for (int i = 0; i < 20; i++) {
int j = i;
pool.execute(() -> {
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info(String.valueOf(j));
});
}
[main] INFO com.phz.juc.ThreadPool - 创建新的任务工作线程: ThreadPool.Worker(task=com.phz.juc.TestPool$$Lambda$3/2121055098@4d405ef7) ,执行任务:com.phz.juc.TestPool$$Lambda$3/2121055098@4d405ef7
[main] INFO com.phz.juc.ThreadPool - 创建新的任务工作线程: ThreadPool.Worker(task=com.phz.juc.TestPool$$Lambda$3/2121055098@3f91beef) ,执行任务:com.phz.juc.TestPool$$Lambda$3/2121055098@3f91beef
[main] INFO com.phz.juc.BlockingQueue - 加入任务队列: com.phz.juc.TestPool$$Lambda$3/2121055098@1a6c5a9e
[Thread-0] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$3/2121055098@4d405ef7
[Thread-1] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$3/2121055098@3f91beef
[main] INFO com.phz.juc.BlockingQueue - 加入任务队列: com.phz.juc.TestPool$$Lambda$3/2121055098@37bba400
[main] INFO com.phz.juc.BlockingQueue - 加入任务队列: com.phz.juc.TestPool$$Lambda$3/2121055098@179d3b25
[main] INFO com.phz.juc.BlockingQueue - 加入任务队列: com.phz.juc.TestPool$$Lambda$3/2121055098@254989ff
[main] INFO com.phz.juc.BlockingQueue - 加入任务队列: com.phz.juc.TestPool$$Lambda$3/2121055098@5d099f62
[main] INFO com.phz.juc.BlockingQueue - 加入任务队列: com.phz.juc.TestPool$$Lambda$3/2121055098@37f8bb67
[main] INFO com.phz.juc.BlockingQueue - 加入任务队列: com.phz.juc.TestPool$$Lambda$3/2121055098@49c2faae
[main] INFO com.phz.juc.BlockingQueue - 加入任务队列: com.phz.juc.TestPool$$Lambda$3/2121055098@20ad9418
[main] INFO com.phz.juc.BlockingQueue - 加入任务队列: com.phz.juc.TestPool$$Lambda$3/2121055098@31cefde0
[main] INFO com.phz.juc.BlockingQueue - 加入任务队列: com.phz.juc.TestPool$$Lambda$3/2121055098@439f5b3d
[main] INFO com.phz.juc.TestPool - 放弃com.phz.juc.TestPool$$Lambda$3/2121055098@1d56ce6a
[main] INFO com.phz.juc.TestPool - 放弃com.phz.juc.TestPool$$Lambda$3/2121055098@5197848c
[main] INFO com.phz.juc.TestPool - 放弃com.phz.juc.TestPool$$Lambda$3/2121055098@17f052a3
[main] INFO com.phz.juc.TestPool - 放弃com.phz.juc.TestPool$$Lambda$3/2121055098@2e0fa5d3
[main] INFO com.phz.juc.TestPool - 放弃com.phz.juc.TestPool$$Lambda$3/2121055098@5010be6
[main] INFO com.phz.juc.TestPool - 放弃com.phz.juc.TestPool$$Lambda$3/2121055098@685f4c2e
[main] INFO com.phz.juc.TestPool - 放弃com.phz.juc.TestPool$$Lambda$3/2121055098@7daf6ecc
[main] INFO com.phz.juc.TestPool - 放弃com.phz.juc.TestPool$$Lambda$3/2121055098@2e5d6d97
[Thread-0] INFO com.phz.juc.TestPool - 0
[Thread-1] INFO com.phz.juc.TestPool - 1
[Thread-0] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$3/2121055098@1a6c5a9e
[Thread-1] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$3/2121055098@37bba400
[Thread-1] INFO com.phz.juc.TestPool - 3
[Thread-0] INFO com.phz.juc.TestPool - 2
[Thread-1] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$3/2121055098@179d3b25
[Thread-0] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$3/2121055098@254989ff
[Thread-0] INFO com.phz.juc.TestPool - 5
[Thread-1] INFO com.phz.juc.TestPool - 4
[Thread-0] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$3/2121055098@5d099f62
[Thread-1] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$3/2121055098@37f8bb67
[Thread-1] INFO com.phz.juc.TestPool - 7
[Thread-0] INFO com.phz.juc.TestPool - 6
[Thread-1] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$3/2121055098@49c2faae
[Thread-0] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$3/2121055098@20ad9418
[Thread-1] INFO com.phz.juc.TestPool - 8
[Thread-0] INFO com.phz.juc.TestPool - 9
[Thread-1] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$3/2121055098@31cefde0
[Thread-0] INFO com.phz.juc.ThreadPool - 正在执行:com.phz.juc.TestPool$$Lambda$3/2121055098@439f5b3d
[Thread-1] INFO com.phz.juc.TestPool - 10
[Thread-0] INFO com.phz.juc.TestPool - 11
[Thread-1] INFO com.phz.juc.ThreadPool - 工作线程被移除:ThreadPool.Worker(task=null)
[Thread-0] INFO com.phz.juc.ThreadPool - 工作线程被移除:ThreadPool.Worker(task=null)
其他拒绝策略
- 调用者自己执行
(blockingQueue, task) -> {
task.run();
}
- 死等
BlockingQueue::put
- 抛出异常
(blockingQueue, task) -> {
throw new RuntimeException("任务执行失败 " + task);
}
- 带超时的等
(blockingQueue, task) -> {
blockingQueue.put(task, 1500, TimeUnit.MILLISECONDS);
}
- 放弃执行
(blockingQueue, task) -> {
log.info("放弃{}", task);
}
3、ThreadPoolExecutor
3.1、线程池状态
ThreadPoolExecutor 使用 int 的高 3 位来表示线程池状态,低 29 位表示线程数量
状态名 | 高 3 位 | 接收新任务 | 处理阻塞队列任务 | 说明 |
---|---|---|---|---|
RUNNING | 111 | Y | Y | |
SHUTDOWN | 000 | N | Y | 不会接收新任务,但会处理阻塞队列剩余 任务 |
STOP | 001 | N | N | 会中断正在执行的任务,并抛弃阻塞队列 任务 |
TIDYING | 010 | - | - | 任务全执行完毕,活动线程为 0 即将进入 终结 |
TERMINATED | 011 | - | - | 终结状态 |
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;
从数字上比较,TERMINATED > TIDYING > STOP > SHUTDOWN > RUNNING (111,最高位为 1,表示负数),这些信息存储在一个原子变量 ctl 中,目的是将线程池状态与线程个数合二为一,这样就可以用一次 CAS 原子操作进行赋值
// rs 为高三位,表示状态, wc 为低 29 位,表示线程个数,然后合并他们
private static int ctlOf(int rs, int wc) { return rs | wc; }
//c 为原始值,ctlOf 返回值为期望值
ctl.compareAndSet(c, ctlOf(targetState, workerCountOf(c))))
3.2、构造方法
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 最大线程数目(减去核心线程数 = 救急线程数)
- keepAliveTime 生存时间 - 针对救急线程 unit 时间单位 - 针对救急线程
- workQueue 阻塞队列
- threadFactory 线程工厂 (可以为线程创建时起个好名字,调试起来方便)
- handler 拒绝策略
其中救急线程用于,核心线程执行的任务都还没结束,阻塞队列也满了,就会看有没有救急线程,有就执行,救急线程执行完毕后,一定的时间(生存时间)后就会销毁,但是核心线程执行完毕后,并不会被销毁,还会在后台存活,如果核心线程,阻塞队列,救急线程都满了,就会执行拒绝策略
工作方式如下:
-
线程池中刚开始没有线程,当一个任务提交给线程池后,线程池会创建一个新线程来执行任务。
-
当线程数达到 corePoolSize 并没有线程空闲,这时再加入任务,新加的任务会被加入 workQueue 队列排队,直到有空闲的线程。
-
如果队列选择了有界队列,那么任务超过了队列大小时,会创建 maximumPoolSize - corePoolSize 数目的线程来救急。
-
如果线程到达 maximumPoolSize 仍然有新任务这时会执行拒绝策略。拒绝策略 JDK 提供了 4 种实现,其它著名框架也提供了实现
- AbortPolicy 让调用者抛出 RejectedExecutionException 异常,这是默认策略
- CallerRunsPolicy 让调用者运行任务
- DiscardPolicy 放弃本次任务
- DiscardOldestPolicy 放弃队列中最早的任务,本任务取而代之
- Dubbo 的实现,在抛出 RejectedExecutionException 异常之前会记录日志,并 dump 线程栈信息,方便定位问题
- Netty 的实现,是创建一个新线程来执行任务
- ActiveMQ 的实现,带超时等待(60s)尝试放入队列,类似我们之前自定义的拒绝策略
- PinPoint (链路追踪)的实现,它使用了一个拒绝策略链,会逐一尝试策略链中每种拒绝策略
-
当高峰过去后,超过 corePoolSize 的救急线程如果一段时间没有任务做,需要结束节省资源,这个时间由 keepAliveTime 和 unit 来控制。
根据这个构造方法,JDK Executors 类中提供了众多工厂方法来创建各种用途的线程池
3.3、若干工厂方法
相关方法可以进入 Executors 类中查看
3.3.1、newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
- 核心线程数 == 最大线程数(没有救急线程被创建),因此也无需超时时间
- 阻塞队列是无界的,可以放任意数量的任务
适用于任务量已知,相对耗时的任务
3.3.2、newCachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
- 核心线程数是 0, 最大线程数是 Integer.MAX_VALUE,救急线程的空闲生存时间是 60s,意味着
- 全部都是救急线程(60s 后可以回收)
- 救急线程可以无限创建
- 队列采用了 SynchronousQueue 实现特点是,它没有容量,没有线程来取是放不进去的(一手交钱、一手交货)
SynchronousQueue<Integer> integers = new SynchronousQueue<>();
new Thread(() -> {
try {
log.info("putting {} ", 1);
integers.put(1);
log.info("{} putted...", 1);
log.info("putting...{} ", 2);
integers.put(2);
log.info("{} putted...", 2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t1").start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
try {
log.info("taking {}", 1);
integers.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t2").start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
try {
log.info("taking {}", 2);
integers.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t3").start();
整个线程池表现为线程数会根据任务量不断增长,没有上限,当任务执行完毕,空闲 1 分钟后释放线程。适合任务数比较密集,但每个任务执行时间较短的情况
3.2.3、newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
适用于希望多个任务排队执行。线程数固定为 1,任务数多于 1 时,会放入无界队列排队。任务执行完毕,这唯一的线程也不会被释放。
只有一个线程,也能叫线程池吗?
-
自己创建一个单线程串行执行任务,如果任务执行失败而终止那么没有任何补救措施,而线程池还会新建一个线程,保证池的正常工作
-
Executors.newSingleThreadExecutor() 线程个数始终为 1,不能修改
- 返回的是一个 FinalizableDelegatedExecutorService ,其中参数才创建的 ThreadPoolExecutor ,这里应用的是装饰器模式,只对外暴露了 ExecutorService 接口,限制了我们只能调用接口的方法,而不能调用 ThreadPoolExecutor 中特有的方法
static class FinalizableDelegatedExecutorService extends DelegatedExecutorService { FinalizableDelegatedExecutorService(ExecutorService executor) { super(executor); } protected void finalize() { super.shutdown(); } }
-
Executors.newFixedThreadPool(1) 初始时为 1,以后还可以修改
- 对外暴露的是 ThreadPoolExecutor 对象,可以强转后调用 setCorePoolSize 等方法进行修改
3.4、提交任务
// 执行任务
void execute(Runnable command);
// 提交任务 task,用返回值 Future 获得任务执行结果
<T> Future<T> submit(Callable<T> task);
// 提交 tasks 中所有任务
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
// 提交 tasks 中所有任务
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
// 提交 tasks 中所有任务,带超时时间
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException;
// 提交 tasks 中所有任务,哪个任务先成功执行完毕,返回此任务执行结果,其它任务取消
<T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException;
// 提交 tasks 中所有任务,哪个任务先成功执行完毕,返回此任务执行结果,其它任务取消,带超时时间
<T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
3.5、关闭线程池
- shutdown
//线程池状态变为 SHUTDOWN,不会接收新任务,但已提交任务会执行完(包括正在执行的和阻塞队列中的),此方法不会阻塞调用线程的执行
public void shutdown() {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
//修改线程池状态
advanceRunState(SHUTDOWN);
//仅会打断空闲线程
interruptIdleWorkers();
onShutdown(); //扩展点 给子类ScheduledThreadPoolExecutor用的
} finally {
mainLock.unlock();
}
//尝试终结
tryTerminate();
}
- shutdownNow
//线程池状态变为 STOP,不会接收新任务,会将任务队列中的任务返回,并用 interrupt 的方式中断正在执行的任务
public List<Runnable> shutdownNow() {
List<Runnable> tasks;
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
checkShutdownAccess();
// 修改线程池状态
advanceRunState(STOP);
// 打断所有线程
interruptWorkers();
// 获取队列中剩余任务
tasks = drainQueue();
} finally {
mainLock.unlock();
}
// 尝试终结
tryTerminate();
return tasks;
}
- 其他方法
// 不在 RUNNING 状态的线程池,此方法就返回 true
boolean isShutdown();
// 线程池状态是否是 TERMINATED
boolean isTerminated();
// 调用 shutdown 后,由于调用线程并不会等待所有任务运行结束,因此如果它想在线程池 TERMINATED 后做些事情,可以利用此方法等待
boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;
4、任务调度线程池
4.1、延时执行
在『任务调度线程池』功能加入之前,可以使用 java.util.Timer 来实现定时功能,Timer 的优点在于简单易用,但由于所有任务都是由同一个线程来调度,因此所有任务都是串行执行的,同一时间只能有一个任务在执行,前一个任务的延迟或异常都将会影响到之后的任务。
Timer timer = new Timer();
TimerTask task1 = new TimerTask() {
@SneakyThrows
@Override
public void run() {
log.info("task 1");
TimeUnit.SECONDS.sleep(2);
}
};
TimerTask task2 = new TimerTask() {
@Override
public void run() {
log.info("task 2");
}
};
// 使用 timer 添加两个任务,希望它们都在 1s 后执行
// 但由于 timer 内只有一个线程来顺序执行队列中的任务,因此『任务1』的延时,影响了『任务2』的执行
timer.schedule(task1, 1000);
timer.schedule(task2, 1000);
使用任务调度线程池改造:
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
// 添加两个任务,希望它们都在 1s 后执行
executor.schedule(() -> {
System.out.println("任务1,执行时间:" + new Date());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, 1000, TimeUnit.MILLISECONDS);
executor.schedule(() -> {
System.out.println("任务2,执行时间:" + new Date());
}, 1000, TimeUnit.MILLISECONDS);
如果其中有一个线程执行报错,并不会影响其他线程的执行
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
// 添加两个任务,希望它们都在 1s 后执行
executor.schedule(() -> {
System.out.println("任务1,执行时间:" + new Date());
int i = 1 / 0;
}, 1000, TimeUnit.MILLISECONDS);
executor.schedule(() -> {
System.out.println("任务2,执行时间:" + new Date());
}, 1000, TimeUnit.MILLISECONDS);
但是希望出现的异常并没有出现,怎么回事?对于异常,我们可以有如下解决办法
- 自己捕捉
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
// 添加两个任务,希望它们都在 1s 后执行
executor.schedule(() -> {
try {
System.out.println("任务1,执行时间:" + new Date());
int i = 1 / 0;
} catch (Exception e) {
e.printStackTrace();
}
}, 1000, TimeUnit.MILLISECONDS);
executor.schedule(() -> {
System.out.println("任务2,执行时间:" + new Date());
}, 1000, TimeUnit.MILLISECONDS);
- 使用 future
ExecutorService pool = Executors.newFixedThreadPool(1);
Future<Boolean> f = pool.submit(() -> {
log.info("task1");
int i = 1 / 0;
return true;
});
log.info("result:{}", f.get());
4.2、定时执行
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
log.debug("start...");
pool.scheduleAtFixedRate(() -> {
log.info("running...");
}, 1, 1, TimeUnit.SECONDS);
如果任务本身执行的时间超过了间隔时间呢?
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
log.debug("start...");
pool.scheduleAtFixedRate(() -> {
log.info("running..." + new Date());
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, 1, 1, TimeUnit.SECONDS);
- 一开始,延时 1s,接下来,由于任务执行时间 > 间隔时间,间隔被『撑』到了 2s,也就是取间隔时间和实际时间的最大值
如果就是希望两个任务之间间隔若干时间执行,可以使用 scheduleWithFixedDelay 方法
ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
log.debug("start...");
pool.scheduleWithFixedDelay(() -> {
log.info("running..." + new Date());
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, 1, 1, TimeUnit.SECONDS);
- 延时 1s,scheduleWithFixedDelay 的间隔是 上一个任务结束 <-> 延时 <-> 下一个任务开始 所以间隔都是 3s
5、Tomcat线程池
- LimitLatch 用来限流,可以控制最大连接个数,类似 JUC 中的 Semaphore
- Acceptor 只负责接受新的 Socket 连接
- Poller 只负责监听 Socket Channel 是否有可读的 IO 事件,一旦可读,封装一个 socketProcessor 任务对象,提交给 Executor 线程池处理
- Executor 中的工作线程最终负责处理请求
Tomcat 线程池也叫 ThreadPoolExecutor ,是根据 JDK 中的修改而来,所以和 JDK 中的稍有不同
- 如果总线程数达到 maximumPoolSize,这时不会立刻抛出 RejectedExecutionException 异常,而是尝试将任务放入队列,如果还是失败,才会抛出该异常
源码 tomcat-catalina-9.0.58
public void execute(Runnable command, long timeout, TimeUnit unit) {
submittedCount.incrementAndGet();
try {
// 如果线程已经被占满了,就会抛出 RejectedExecutionException 异常
executeInternal(command);
} catch (RejectedExecutionException rx) {
if (getQueue() instanceof TaskQueue) {
// 如果 Executor 接近最大池大小,并发调用 execute() 可能会导致(由于 Tomcat 使用 TaskQueue)某些任务被拒绝而不是排队。如果发生这种情况,请将它们添加到队列中。
// 该阻塞队列也已经被扩展
final TaskQueue queue = (TaskQueue) getQueue();
try {
// 尝试加入队列中
if (!queue.force(command, timeout, unit)) {
// 如果加入失败才会抛出异常
submittedCount.decrementAndGet();
throw new RejectedExecutionException(sm.getString("threadPoolExecutor.queueFull"));
}
} catch (InterruptedException x) {
submittedCount.decrementAndGet();
throw new RejectedExecutionException(x);
}
} else {
submittedCount.decrementAndGet();
throw rx;
}
}
}
Connector 配置项,对应 Tomcat server.xml 文件 Connector 标签
配置项 | 默认值 | 说明 |
---|---|---|
acceptorThreadCount | 1 | acceptor 线程数量 |
pollerThreadCount | 1 | poller 线程数量 |
minSpareThreads | 10 | 核心线程数,即 corePoolSize |
maxThreads | 200 | 最大线程数,即 maximumPoolSize |
executor | - | Executor 名称,用来引用下面的 Executor |
- acceptor:线程数量为 1 就好,没有请求的时候它是阻塞的,没有必要使用太多线程
- poller:采用了多路复用的思想,能监听很多的 Channel 读写事件,所以 1 个也可以了
- executor:就是一个标签引用下面的配置,如果配置了,就会覆盖 minSpareThreads 和 maxThreads
Executor 线程配置,对应 Tomcat server.xml 文件 Executor 标签(默认被注释掉了)
配置项 | 默认值 | 说明 |
---|---|---|
threadPriority | 5 | 线程优先级 |
daemon | true | 是否守护线程 |
minSpareThreads | 25 | 核心线程数,即 corePoolSize |
maxThreads | 200 | 最大线程数,即 maximumPoolSize |
maxIdleTime | 60000 | 线程生存时间,单位是毫秒,默认值即 1 分钟 |
maxQueueSize | Integer.MAX_VALUE | 队列长度 |
prestartminSpareThreads | false | 核心线程是否在服务器启动时启动 |
- daemon:tomcat 中的线程都是守护线程,一旦主服务关闭,其余线程都将关闭
- maxIdleTime:也就是救急线程的存活时间
- maxQueueSize:阻塞队列的长度,默认是无界队列,如果服务器压力过大,可能会造成任务的堆积
- prestartminSpareThreads:核心线程的创建是否是懒惰的
既然阻塞队列是无界的,那救急线程是不是就没有用了呢,因为在 JDK 中,如果阻塞队列是有界的,只有当阻塞队列满了,才会创建救急线程救急,这里阻塞队列是
一个无界的,那救急线程不久没用了嘛
其实就是刚才的 Tomcat 源码中,TaskQueue 已经做了扩展,Tomcat 中会对正在执行的任务计数,提交会加一,结束会减一,如果提交的任务数目前还小于核心线程数,直接加入阻塞队列等待执行,如果已经大于核心线程了,现在还不会立即加入阻塞队列,会先判断提交的任务数是否大于最大的线程数,如果小于,就创建救急线程执行,如果已经大于了,才会加入阻塞队列