1、自定义拒绝策略接口
package com.tk.threadPool;
/**
* 拒绝策略
*
* @author taoke
* @date 2023/3/23
*/
@FunctionalInterface
public interface RejectPolicy<T> {
/**
* 拒绝策略规则
*
* @param queue 阻塞队列
* @param task 任务
*/
void reject(BlockingQueue<T> queue, T task);
}
2、自定义任务队列
package com.tk.threadPool;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 阻塞队列
*
* @author taoke
* @date 2023/3/23
*/
@Slf4j
class BlockingQueue<T> {
/**
* 任务队列
*/
private final Deque<T> queue = new ArrayDeque<>();
/**
* 锁
*/
private final ReentrantLock lock = new ReentrantLock();
/**
* 队列满的waitSet
*/
private final Condition fullWaitSet = lock.newCondition();
/**
* 队列为空的waitSet
*/
private final Condition emptyWaitSet = lock.newCondition();
/**
* 队列容量
*/
private final int capacity;
public BlockingQueue(int capacity) {
this.capacity = capacity;
}
/**
* 带超时阻塞获取
*
* @param timeout 超时时间
* @param unit 时间单位
* @return 任务
*/
public T poll(long timeout, TimeUnit unit) {
lock.lock();
try {
// 将 timeout 统一转换为 纳秒
long nanos = unit.toNanos(timeout);
while (queue.isEmpty()) {
try {
// 返回值是剩余时间
if (nanos <= 0) {
return null;
}
nanos = emptyWaitSet.awaitNanos(nanos);
} catch (InterruptedException e) {
e.printStackTrace();
log.debug(e.getMessage(), e);
}
}
T t = queue.removeFirst();
fullWaitSet.signal();
return t;
} finally {
lock.unlock();
}
}
/**
* 阻塞获取
*
* @return 任务
*/
public T take() {
lock.lock();
try {
while (queue.isEmpty()) {
try {
emptyWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
log.debug(e.getMessage(), e);
}
}
T t = queue.removeFirst();
fullWaitSet.signal();
return t;
} finally {
lock.unlock();
}
}
/**
* 阻塞添加
*
* @param task 任务
*/
public void put(T task) {
lock.lock();
try {
while (queue.size() == capacity) {
try {
log.debug("等待加入任务队列 {} ...", task);
fullWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
log.debug(e.getMessage(), e);
}
}
log.debug("加入任务队列 {}", task);
queue.addLast(task);
emptyWaitSet.signal();
} finally {
lock.unlock();
}
}
/**
* 带超时时间阻塞添加
*
* @param task 任务
* @param timeout 超时时间
* @param timeUnit 超时单位
* @return 是否添加成功
*/
public boolean offer(T task, long timeout, TimeUnit timeUnit) {
lock.lock();
try {
long nanos = timeUnit.toNanos(timeout);
while (queue.size() == capacity) {
try {
if (nanos <= 0) {
return false;
}
log.debug("等待加入任务队列 {} ...", task);
nanos = fullWaitSet.awaitNanos(nanos);
} catch (InterruptedException e) {
e.printStackTrace();
log.debug(e.getMessage(), e);
}
}
log.debug("加入任务队列 {}", task);
queue.addLast(task);
emptyWaitSet.signal();
return true;
} finally {
lock.unlock();
}
}
/**
* 获取队列大小
*
* @return 队列大小
*/
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(this, task);
} else {
//队列有空闲
log.debug("加入任务队列 {}", task);
queue.addLast(task);
emptyWaitSet.signal();
}
} finally {
lock.unlock();
}
}
}
3、自定义线程池
package com.tk.threadPool;
import lombok.extern.slf4j.Slf4j;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* 自定义线程池
*
* @author taoke
* @date 2023/3/23
*/
@Slf4j
class ThreadPool {
/**
* 任务队列
*/
private final BlockingQueue<Runnable> taskQueue;
/**
* 工作线程集合
*/
private final Set<Worker> workers = new HashSet<>();
/**
* 核心线程数
*/
private final int coreSize;
/**
* 获取任务时的超时时间
*/
private final long timeout;
/**
* 获取任务时的超时时间单位
*/
private final TimeUnit timeUnit;
/**
* 拒绝策略
*/
private final RejectPolicy<Runnable> rejectPolicy;
public ThreadPool(int coreSize, int queueCapacity, long timeout, TimeUnit timeUnit, RejectPolicy<Runnable> rejectPolicy) {
this.coreSize = coreSize;
this.taskQueue = new BlockingQueue<>(queueCapacity);
this.timeout = timeout;
this.timeUnit = timeUnit;
this.rejectPolicy = rejectPolicy;
}
/**
* 执行任务
* 工作线程已满可以尝试2种方式
* 1) 死等 taskQueue.put(task);
* 2) 带超时等待 taskQueue.tryPut(rejectPolicy, task);
* 3) 让调用者放弃任务执行 log.debug("放弃{}", task);
* 4) 让调用者抛出异常 throw new RuntimeException("任务执行失败 " + task);
* 5) 让调用者自己执行任务 task.run();
*
* @param task 任务
*/
public void execute(Runnable task) {
// 当任务数没有超过 coreSize 时,直接交给 worker 对象执行
// 如果任务数超过 coreSize 时,加入任务队列暂存
synchronized (workers) {
if (workers.size() < coreSize) {
Worker worker = new Worker(task);
log.debug("添加 worker{}, {}", worker, task);
workers.add(worker);
worker.start();
} else {
taskQueue.tryPut(rejectPolicy, task);
}
}
}
/**
* 工作线程
*/
class Worker extends Thread {
private Runnable task;
public Worker(Runnable task) {
this.task = task;
}
/**
* 执行任务
* 1) 当 task 不为空,执行任务
* 2) 当 task 执行完毕,再接着从任务队列获取任务并执行
*/
@Override
public void run() {
while (task != null || (task = taskQueue.poll(timeout, timeUnit)) != null) {
try {
log.debug("正在执行...{}", task);
task.run();
} catch (Exception e) {
e.printStackTrace();
log.debug(e.getMessage(), e);
} finally {
task = null;
}
}
//任务执行完毕,移除当前线程
synchronized (workers) {
log.debug("worker 被移除{}", this);
workers.remove(this);
}
}
}
}
4、测试类
package com.tk.threadPool;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
/**
* 测试类
*
* @author taoke
* @date 2023/3/23
*/
@Slf4j
public class ThreadPoolTest {
/**
* 拒绝策略,队列中任务数量达到queueCapacity,任然有任务加入队列
* 1. 死等
* queue.put(task);
* 2) 带超时等待
* queue.offer(task, 2000, TimeUnit.MILLISECONDS);
* 3) 让调用者放弃任务执行
* log.debug("放弃{}", task);
* 4) 让调用者抛出异常
* throw new RuntimeException("任务执行失败 " + task);
* 5) 让调用者自己执行任务
* task.run();
*
* @param args 参数
*/
public static void main(String[] args) {
ThreadPool threadPool = new ThreadPool(2, 3, 1, TimeUnit.SECONDS, (queue, task) -> {
boolean offer = queue.offer(task, 2000, TimeUnit.MILLISECONDS);
log.debug("添加任务到队列是否成功:{}", offer);
});
for (int i = 0; i < 6; i++) {
int j = i;
threadPool.execute(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
log.debug(e.getMessage(), e);
}
log.debug("{}", j);
});
}
}
}