package org.example.Pool;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
@Slf4j(topic = "c.TestPool")
public class TestPool {
public static void main(String[] args) {
ThreadPool threadPool = new ThreadPool(1,1000,TimeUnit.MICROSECONDS,1,(queue,task)->{
//1.死等
queue.put(task);
//2.带超时等待
queue.offer(task,500,TimeUnit.MICROSECONDS);
//3.调用者放弃任务执行
log.debug("放弃任务"); //不进行任何操作
//4.让调用者抛出异常
// throw new RuntimeException("任务失败"+task);
//5.让调用者自己执行任务
task.run();
});
for (int i = 0; i < 3; i++) {
int j = i;
threadPool.execute(()->{
try {
Thread.sleep(1000);
}catch (InterruptedException e){
e.printStackTrace();
}
});
}
}
}
@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 unit;
private RejectPolicy<Runnable> rejectPolicy;
//执行任务
public void execute(Runnable task){
synchronized (workers){
//当任务数没有超过coresize时,直接交给woker就可以
//,如果超过了,那么就把任务放在任务队列
if(workers.size() < coreSize){
Worker worker = new Worker(task);
workers.add(worker);
worker.start();
}else {
//任务数量超过了线程核心数量,把任务交给任务队列
// taskQueue.put(task);
//拒绝策列 并且采用策略模式(函数式接口),将操作交给调用者
taskQueue.tryPut(rejectPolicy,task);
}
}
}
public ThreadPool(int coreSize, long timeout, TimeUnit unit,int queueCapcity,RejectPolicy<Runnable> rejectPolicy) {
this.coreSize = coreSize;
this.timeout = timeout;
this.unit = unit;
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.poll(1000,TimeUnit.SECONDS)) != null){
try {
task.run();
}catch (Exception e){
e.printStackTrace();
}finally {
task = null;
}
}
synchronized (workers){
workers.remove(this);
}
}
}
}
class BlockingQueue<T>{
//1.任务队列
private Deque<T> queue = new ArrayDeque<>();
//锁
private ReentrantLock lock = new ReentrantLock();
//生产者条件变量
private Condition fullWithSet = lock.newCondition();
//消费者条件变量
private Condition emptyWithSet = lock.newCondition();
//容量
private int capcity;
public BlockingQueue(int capcity) {
this.capcity = capcity;
}
//带超时的阻塞获取
public T poll(long time, TimeUnit unit){
//将超时的时间全部转换为纳秒
long nanos = unit.toNanos(time);
lock.lock();
try {
//如果这个队列是空的,那么我们让这个线程直接进入等待,等到队列不空的时候被唤醒
while (queue.isEmpty()){
try{
if (nanos <= 0){
return null;
}
//返回的是剩余时间
nanos = emptyWithSet.awaitNanos(nanos);
}catch (InterruptedException e){
e.printStackTrace();
}
}
T t = queue.removeFirst();
fullWithSet.signal();
return t;
}finally {
lock.unlock();
}
}
//阻塞获取
public T take(){
lock.lock();
try {
//如果这个队列是空的,那么我们让这个线程直接进入等待,等到队列不空的时候被唤醒
while (queue.isEmpty()){
try{
emptyWithSet.await();
}catch (InterruptedException e){
e.printStackTrace();
}
}
T t = queue.removeFirst();
fullWithSet.signal();
return t;
}finally {
lock.unlock();
}
}
//阻塞添加
public void put(T element){
lock.lock();
//先判断队列是否是满的,如果队列已经满了,这个线程直接阻塞等待
try {
while (queue.size() == capcity){
try {
fullWithSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//将任务添加到队列的尾部,并且唤醒等待取任务的线程
queue.addLast(element);
emptyWithSet.signal();
}finally {
lock.unlock();
}
}
//带超时时间的阻塞方法
public boolean offer(T task, long time, TimeUnit unit){
//转换时间
long nanos = unit.toNanos(time);
lock.lock();
//先判断队列是否是满的,如果队列已经满了,这个线程直接阻塞等待
try {
while (queue.size() == capcity){
if (nanos <= 0){
return false;
}
try {
nanos = fullWithSet.awaitNanos(nanos);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//将任务添加到队列的尾部,并且唤醒等待取任务的线程
queue.addLast(task);
emptyWithSet.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){
//这里的this是把queue和task传出去
rejectPolicy.reject(this,task);
}else {
queue.addLast(task);
emptyWithSet.signal();
}
}finally {
lock.unlock();
}
}
}
简单线程池代码(使用策略模式解决任务队列已经满了)
最新推荐文章于 2024-07-19 21:03:45 发布