当前位置:网站首页>多线程之自定义线程池
多线程之自定义线程池
2022-08-10 00:44:00 【七国的天下,我要九十九】
1 自义定线程池
1定义
自定义线程池组成部分: 核心线程数,等待超时时间,等待时间单位,任务队列,拒绝策略.
2 组成部分
1 自定义拒绝策略接口
// 拒绝策略
@FunctionalInterface
interface RejectPolicy<T> {
void reject(BlockingQueue<T> queue, T task);
}
拒绝策略接口,主要用来线程池做拒绝任务实现,根据不同实现的子类,来定义拒绝的策略,接口本身定义为函数式接口,更加灵活由调用者控制.
2 自定义任务队列
class BlockingQueue<T> {
// 1. 任务队列
private Deque<T> queue = new ArrayDeque<>();
// 2. 锁
private ReentrantLock lock = new ReentrantLock();
// 3. 生产者条件变量
private Condition fullWaitSet = lock.newCondition();
// 4. 消费者条件变量
private Condition emptyWaitSet = lock.newCondition();
// 5. 容量
private int capcity;
public BlockingQueue(int capcity) {
this.capcity = capcity;
}
// 带超时阻塞获取
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();
}
}
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) {
e.printStackTrace();
}
}
T t = queue.removeFirst();
fullWaitSet.signal();
return t;
} finally {
lock.unlock();
}
}
// 阻塞添加
public void put(T task) {
lock.lock();
try {
while (queue.size() == capcity) {
try {
log.debug("等待加入任务队列 {} ...", task);
fullWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.debug("加入任务队列 {}", task);
queue.addLast(task);
emptyWaitSet.signal();
} finally {
lock.unlock();
}
}
// 带超时时间阻塞添加
public boolean offer(T task, long timeout, TimeUnit timeUnit) {
lock.lock();
try {
long nanos = timeUnit.toNanos(timeout);
while (queue.size() == capcity) {
try {
if(nanos <= 0) {
return false;
}
log.debug("等待加入任务队列 {} ...", task);
nanos = fullWaitSet.awaitNanos(nanos);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.debug("加入任务队列 {}", task);
queue.addLast(task);
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 task) {
lock.lock();
try {
// 判断队列是否满
if(queue.size() == capcity) {
rejectPolicy.reject(this, task);
} else {
// 有空闲
log.debug("加入任务队列 {}", task);
queue.addLast(task);
emptyWaitSet.signal();
}
} finally {
lock.unlock();
}
}
}
任务队列, 主要用来暂存任务. 当核心线程数超过任务数量时,需要将任务暂存在队列中,当队列中存放任务数量满载,会执行拒绝策略.
3 自定义线程池
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 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.put(task);
// 1) 死等
// 2) 带超时等待
// 3) 让调用者放弃任务执行
// 4) 让调用者抛出异常
// 5) 让调用者自己执行任务
taskQueue.tryPut(rejectPolicy, task);
}
}
}
public ThreadPool(int coreSize, long timeout, TimeUnit timeUnit, int queueCapcity,
RejectPolicy<Runnable> rejectPolicy) {
this.coreSize = coreSize;
this.timeout = timeout;
this.timeUnit = timeUnit;
this.taskQueue = new BlockingQueue<>(queueCapcity);
this.rejectPolicy = rejectPolicy;
}
class Worker extends Thread{
private Runnable task;
public Worker(Runnable task) {
this.task = task;
}
@Override
public void run() {
// 执行任务
// 1) 当 task 不为空,执行任务
// 2) 当 task 执行完毕,再接着从任务队列获取任务并执行
// while(task != null || (task = taskQueue.take()) != null) {
while(task != null || (task = taskQueue.poll(timeout, timeUnit)) != null) {
try {
log.debug("正在执行...{}", task);
task.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
task = null;
}
}
synchronized (workers) {
log.debug("worker 被移除{}", this);
workers.remove(this);
}
}
}
}
线程池,主要是用来获取执行任务的对象.根据自定义的任务队列,拒绝策略,构造出线程池, 执行任务时,从线程池中,获取线程,执行任务,当任务数大于核心线程数,则会添加到任务队列, 当任务队列已满,则会执行拒绝策略.
4 测试
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) 让调用者放弃任务执行
// log.debug("放弃{}", task);
// 4) 让调用者抛出异常
// throw new RuntimeException("任务执行失败 " + task);
// 5) 让调用者自己执行任务
task.run();
});
for (int i = 0; i < 4; i++) {
int j = i;
threadPool.execute(() -> {
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("{}", j);
});
}
}
执行任务时,根据调用者不同的需求,来自定义不同的拒绝策略,起到既满足业务需求,又能提高代码效率. (如JDK代码中, 也可将不同拒绝策略定义成枚举,然后更加不同枚举走不同的拒绝策略)
边栏推荐
- 对修饰器的实验支持功能在将来的版本中可能更改。在 “tsconfig“ 或 “jsconfig“ 中设置 “experimentalDecorators“ 选项以删除此警告
- Xi'an biotin-tetrapolyethylene glycol-amide-4phenol light yellow semi-solid
- 【软考软件评测师】软件测试基础知识
- win10重装系统后没声音怎么办?
- el-input保留一位小数点
- mstsc/Mstsc (Microsoft terminal services client)远程桌面连接
- 生物素叠氮化物中的(CAS:1527486-16-3TAMRA-azide-PEG3-Biotin)反应的特点!
- 365 days challenge LeetCode1000 questions - Day 052 Step by step summation to get the minimum value of positive numbers Greedy
- unity 报错 Unsafe code may only appear if compiling with /unsafe. Enable “Allow ‘unsafe‘ code“ in Pla
- 【ROS2原理10】Interface数据的规定
猜你喜欢
GB28181 sip和RTSP(Real-Time Streaming Protocol)实时流控制协议
[LeetCode] Find the sum of the numbers from the root node to the leaf node
assert利用蚁剑登录
为什么字符串一旦创建就不可以改变?
Data storage - the C language
Penetration Testing and Offensive and Defense Confrontation - Vulnerability Scanning & Logic Vulnerability (Part1)
Pyscript,创建一个能执行crud操作的网页应用
【无标题】
【CAS:41994-02-9 |Biotinyl tyramide】Biotinyl tyramide price
基于设计稿识别的可视化低代码系统实践
随机推荐
ASEMI整流桥GBJ1010参数,GBJ1010规格,GBJ1010封装
跨部门沟通的技巧
Are the numbers entered symmetrical?
对修饰器的实验支持功能在将来的版本中可能更改。在 “tsconfig“ 或 “jsconfig“ 中设置 “experimentalDecorators“ 选项以删除此警告
How to add control panel to right click menu in win7
有PEG-Biotin参与的(CAS:1778736-18-7)Biotin-PEG4-OH广泛用于分子靶点检测
【Grpc】简介
-Pickling peanuts-
[obs] obsqsv11 hard coding and comparison with metartc codec
Minimum number of steps to get out of the maze 2
Sikuli's Automated Testing Technology Based on Pattern Recognition
-Chess game-
Win7怎么把控制面板添加到右键菜单
生物素叠氮化物中的(CAS:1527486-16-3TAMRA-azide-PEG3-Biotin)反应的特点!
Solving for the number of mines
【LeetCode】求根节点到叶节点数字之和
R语言使用cox函数构建生存分析回归模型、使用subgroupAnalysis进行亚组分析并可视化森林图
mstsc/Mstsc (Microsoft terminal services client)远程桌面连接
eyb:Redis学习(4)
3511. 倒水问题