一、 线程池
线程池:一个容纳多个线程的容器,容器中的线程可以重复使用,省去了频繁创建和销毁线程对象的操作。
线程池作用:
- 降低资源消耗,减少了创建和销毁线程的次数,每个工作线程都可以被重复利用,可执行多个任务。
- 提高响应速度,当任务到达时,如果有线程可以立即开始执行任务,无需等待新线程的创建。由于减少了线程创建和销毁的延迟,应用程序能够更快地响应新的任务请求。
- 提高线程的客观理性:如果无限制的创建线程,不仅会消耗系统资源,还会降低系统的稳定新,使用线程池可以进行统一的分配,调优和监控。
线程池的核心思想:线程服用,同一个线程可以被重复使用,来处理多个任务。
池化技术:
1.1 自定义线程池
public class demo4 {
public static void main(String[] args) {
ThreadPool threadPool = new ThreadPool(
1, 1000, TimeUnit.MILLISECONDS, 1,
(queue, task) -> {
// 1.死等
// queue.put(task);
// 2.带超时等待
// queue.offer(task, 1500, TimeUnit.MILLISECONDS);
// 3.让调用者放弃任务执行
// System.out.println("放弃");
// 4.让调用者自己抛出异常
// throw new RuntimeException();
// 5.让调用者自己运行任务
task.run();
}
);
for (int i = 0; i < 10; i++) {
int j = i;
threadPool.execute(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("aaa" + j);
});
}
}
}
class BlockingQueue<T> {
// 任务队列
private Deque<T> queue = new ArrayDeque<>();
// 锁
private ReentrantLock lock = new ReentrantLock();
// 生产者条件变量
private Condition fullWaitSet = lock.newCondition();
// 消费者条件变量
private Condition emptyWaitSet = lock.newCondition();
private int capacity;
public BlockingQueue(int capacity) {
this.capacity = capacity;
}
// 添加元素
public void put(T element) {
lock.lock();
try {
// 首先看队列是否已满
while (queue.size() == capacity) {
try {
fullWaitSet.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
queue.addLast(element);
emptyWaitSet.signalAll();
} finally {
lock.unlock();
}
}
public T poll(long mills, TimeUnit unit) {
lock.lock();
try {
long time = unit.toNanos(mills);
while (queue.isEmpty()) {
try {
if (time <= 0) {
return null;
}
time = emptyWaitSet.awaitNanos(time);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
T t = queue.removeFirst();
fullWaitSet.signal();
return t;
} finally {
lock.unlock();
}
}
// 获取元素
public T take() {
lock.lock();
try {
// 如果队列为空,则等待
while (queue.isEmpty()) {
try {
emptyWaitSet.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
T element = queue.removeFirst();
fullWaitSet.signal();
return element;
} finally {
lock.unlock();
}
}
public boolean offer(T element, long mills, TimeUnit unit) {
lock.lock();
try {
long time = unit.toNanos(mills);
while (queue.size() == capacity) {
if (time <= 0) {
return false;
}
try {
time = fullWaitSet.awaitNanos(time);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
queue.addLast(element);
emptyWaitSet.signal();
return true;
} finally {
lock.unlock();
}
}
public int size() {
lock.lock();
try {
return queue.size();
} finally {
lock.unlock();
}
}
public void tryPut(RejectPolicy<T> rejectPolicy, T element) {
lock.lock();
try {
if (queue.size() == capacity) {
rejectPolicy.reject(this, element);
} else {
queue.addLast(element);
emptyWaitSet.signal();
}
} finally {
lock.unlock();
}
}
}
@FunctionalInterface
interface RejectPolicy<T> {
void reject(BlockingQueue<T> queue, T task);
}
// 线程池
class ThreadPool {
// 任务队列
private BlockingQueue<Runnable> taskQueue;
// 线程集合
private HashSet<Worker> workers = new HashSet<>();
// 核心线程数
private int coreSize;
// 获取任务的超时时间
private long timeout;
private TimeUnit timeUnit;
// 拒绝策略
private RejectPolicy<Runnable> rejectPolicy;
public ThreadPool(int coreSize, long timeout, TimeUnit timeUnit, int queueCapacity, RejectPolicy<Runnable> rejectPolicy) {
this.taskQueue = new BlockingQueue<>(queueCapacity);
this.coreSize = coreSize;
this.timeout = timeout;
this.timeUnit = timeUnit;
this.rejectPolicy = rejectPolicy;
}
class Worker extends Thread {
private Runnable task;
public Worker(Runnable task) {
this.task = task;
}
@Override
public void run() {
while (task != null || (task = taskQueue.poll(timeout, timeUnit)) != null) {
try {
task.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
task = null;
}
}
// 如果一直没有任务了,那就销毁该线程
synchronized (workers) {
workers.remove(this);
}
}
}
public void execute(Runnable task) {
synchronized (workers) {
// 如果当前线程总数小于核心线程数,可以直接创建线程
if (workers.size() < coreSize) {
Worker worker = new Worker(task);
workers.add(worker);
worker.start();
} else {
// 执行拒绝策略
taskQueue.tryPut(rejectPolicy, task);
}
}
}
}
- 阻塞队列
BlockingQueue
用于暂存来不及被线程执行的任务- 也可以说是平衡生产者和消费者执行速度的差异。
- 里面的获取任务和放入任务用到了
生产者消费者模式
- 线程池中对Thread进行了再次的封装,封装为Worker
- 在调用任务对象的run方法时,线程会去执行该任务,执行完毕后还会到阻塞队列中获取新任务来执行。
- 线程池中执行任务的主要方法为
execute
方法- 执行时要判断正在执行的线程数是否大于了线程池容量
1.2 ThreadPoolExecutor
1.2.1 线程池状态
ThreadPoolExecutor 使用int的高三位来表示线程池状态,低29为表示线程数量。
状态名 | 高3位 | 接收新任务 | 处理阻塞队列任务 | 说明 |
---|---|---|---|---|
RUNNING | 111 | Y | Y | |
SHUTDOWN | 000 | N | Y | 不会接受新任务,但会处理阻塞队列剩余队伍 |
STOP | 001 | N | N | 会中断正在执行的任务,并抛弃阻塞队列任务。 |
TIDYING | 010 | - | - | 任务全执行完毕,活动线程为0,即将进入终结 |
TERMINATED | 011 | - | - | 终结状态 |
从数字上比较,TERMINATED > TIDYING > STOP > SHUTDOWN > RUNNING
为什么要将线程池状态和线程数量存在一个变量里面呢?
目的是将线程池状态与线程个数合并,这样在赋值的时候就可以使用一次CAS原子操作进行赋值。
// c 为旧值, ctlOf 返回结果为新值
ctl.compareAndSet(c, ctlOf(targetState, workerCountOf(c))));
// rs 为高 3 位代表线程池状态, wc 为低 29 位代表线程个数,ctl 是合并它们
private static int ctlOf(int rs, int wc) {
return rs | wc; }
1.2.2 构造方法
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
- corePoolSize:核心线程数(最多保留的线程数)
- maximumPoolSize:最大线程数目
- keepAliveTime:生存时间(针对救急线程)
- workQueue:阻塞队列
- threadFactory:线程工程(可以给线程创建时起个好名字)
- handler:拒绝策略
工厂方式:
- 线程池刚开始没有线程,当一个任务提交给线程池后,线程池会创建一个新线程来执行任务。
- 当线程数达到corePoolSize而且没有线程空闲,这时再加入任务,新加的任务会被加入workQueue队列排队,直到有空闲的线程。
- 如果队列选择了有界队列,那么任务超过了队列大小时,会创建
maximumPoolSize - corePoolSize
个救济线程来救济。 - 如果线程到达maximumPoolSize仍然有新任务,这时会执行拒绝策略。拒绝策略 jdk 提供了 4 种实现,其它 著名框架也提供了实现
- AbortPolicy 让调用者抛出 RejectedExecutionException 异常,这是默认策略
- DiscardPolicy 放弃本次任务
- DiscardOldestPolicy 放弃队列中最早的任务,本任务取而代之
- Dubbo 的实现,在抛出 RejectedExecutionException 异常之前会记录日志,并 dump 线程栈信息,方便定位问题
- Netty 的实现,是创建一个新线程来执行任务
- ActiveMQ 的实现,带超时等待(60s)尝试放入队列,类似我们之前自定义的拒绝策略
- PinPoint 的实现,它使用了一个拒绝策略链,会逐一尝试策略链中每种拒绝策略
- 当高峰过去后,超过corePoolSize 的救急线程如果一段时间没有任务做,需要结束节省资源,这个时间由 keepAliveTime 和 unit 来控制。
根据这个构造方法,JDK Executors 类中提供了众多工厂方法来创建各种用途的线程池。
1.2.3 newFixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
- 核心线程数==最大线程数(没有救急线程被创建)
- 阻塞队列是无界的,可以放任意数量的任务。
该线程池适用于任务量已知,相对耗时的任务。
1.2.4 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.debug("putting {} ", 1);
integers.put(1);
log.debug("{} putted...", 1);
log.debug("putting...{} ", 2);
integers.put(2);
log.debug("{} putted...", 2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t1").start();
sleep(1);
new Thread(() -> {
try {
log.debug("taking {}", 1);
integers.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t2").start();
sleep(1);
new Thread(() -> {
try {
log.debug("taking {}", 2);
integers.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t3").start();
11:48:15.500 c.TestSynchronousQueue [t1] - putting 1
11:48:16.500 c.TestSynchronousQueue [t2] - taking 1
11:48:16.500 c.TestSynchronousQueue [t1] - 1 putted...
11:48:16.500 c.TestSynchronousQueue [t1] - putting...2
11:48:17.502 c.TestSynchronousQueue [t3] - taking 2
11:48:17.503 c.TestSynchronousQueue [t1] - 2 putted...
整个线程池表现为线程数会根据任务量不断增长,没有上限,当任务执行完毕,空闲 1分钟后释放线程。 适合任务数比较密集,但每个任务执行时间较短的情况。
1.2.5 newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
使用场景:
希望多个任务排队执行。线程数固定为1,任务数多于1时,会放入无界队列排队。任务执行完毕,这唯一的线程也不会被释放。
区别:
- 自己创建一个单线程串行执行任务,如果任务执行失败而终止那么没有任何补救措施,而线程池还会创建一个线程,保证池的正常工作。
- Executors.newSingleThreadExecutor() 线程个数始终为1,不能修改FinalizableDelegatedExecutorService 应用的是装饰器模式,只对外暴露了 ExecutorService 接口,因 此不能调用 ThreadPoolExecutor 中特有的方法
- Executors.newFixedThreadPool(1) 初始时为1,以后还可以修改 对外暴露的是 ThreadPoolExecutor 对象,可以强转后调用 setCorePoolSize 等方法进行修改
1.2.6 提交任务
// 执行任务
void execute(Runnable command);
// 提交任务 task,用返回值 Future 获得任务执行结果
<T> Future<T> submit(Callable<T> task);
// 提交 tasks 中所有任务
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T