@Slf4j(topic = "c.TestPool")
public class Singleton {
public static void main(String[] args) {
ThreadPool threadPool = new ThreadPool(2,
1000, TimeUnit.MILLISECONDS, 1, (queue, task)->{
// 1) 放到任务队列(满的话主线程死等)
queue.put(task);
// 2) 放到任务队列(满的话主线程超时等待)
// queue.putWithTimeOut(task, 1500, TimeUnit.MILLISECONDS);
// 3) 调用者放弃任务执行
// log.debug("放弃{}", task);
// 4) 调用者抛出异常
// throw new RuntimeException("任务执行失败 " + task);
// 5) 调用者自己执行任务
// task.run();
});
for (int i = 0; i < 5; i++) {
int j = i;
threadPool.execute(() -> {
// task
log.debug("{}",j);
});
}
}
}
// 任务队列满时的拒绝策略
@FunctionalInterface
interface RejectPolicy<T> {
void reject(BlockingQueue<T> queue, T task);
}
// 线程池
@Slf4j(topic = "c.ThreadPool")
class ThreadPool {
// 任务队列
private BlockingQueue<Runnable> taskQueue;
// 线程集合
private HashSet<Worker> threads = new HashSet<>();
// 线程数上限
private int coreSize;
// 获取任务时的超时时间
private long timeout;
private TimeUnit timeUnit;
private RejectPolicy<Runnable> rejectPolicy;
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) {
super(task,String.format("线程%s",threads.size() + 1));
this.task = task;
}
@Override
public void run() {
// 执行完task后,并不立即结束,看还有没有下一个task
while(task != null || (task = taskQueue.get()) != null) {
try {
task.run();
log.debug("线程:{}将任务:{}执行完毕",this.getName(),Integer.toHexString(task.hashCode()));
} catch (Exception e) {
e.printStackTrace();
} finally {
task = null;
}
}
synchronized (threads) {
log.debug("移除线程:{}",this.getName());
threads.remove(this);
}
}
}
// 执行任务
public void execute(Runnable task) {
synchronized (threads) {
if(threads.size() < coreSize) {
Worker worker = new Worker(task);
threads.add(worker);
log.debug("新增线程:{},任务:{}",worker.getName(),Integer.toHexString(task.hashCode()));
worker.start();
} else {
// 活跃线程数(正在执行任务的 + 等待新任务的)等于容量
taskQueue.tryPut(rejectPolicy, task);
}
}
}
}
// 任务队列
@Slf4j(topic = "c.BlockingQueue")
class BlockingQueue<T> {
// 任务队列
private Deque<T> queue = new ArrayDeque<>();
// 锁
private ReentrantLock lock = new ReentrantLock();
// (等待任务队列空位)
private Condition taskPuttersWaitSet = lock.newCondition();
// (线程池中的线程等待任务)
private Condition taskGettersWaitSet = lock.newCondition();
// 队列容量
private int taskQueueCapacity;
public BlockingQueue(int taskQueueCapacity) {
this.taskQueueCapacity = taskQueueCapacity;
}
// 获取任务
public T getWithTimeOut(long timeout, TimeUnit unit) {
lock.lock();
try {
long nanos = unit.toNanos(timeout);
while (queue.isEmpty()) {
try {
if (nanos <= 0) {
return null;
}
nanos = taskGettersWaitSet.awaitNanos(nanos);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T t = queue.removeFirst();
taskPuttersWaitSet.signal();
return t;
} finally {
lock.unlock();
}
}
public T get() {
lock.lock();
try {
while (queue.isEmpty()) {
try {
log.debug("线程:{}等待新任务",Thread.currentThread().getName());
taskGettersWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T t = queue.removeFirst();
log.debug("线程:{}拿到新任务:{}",Thread.currentThread().getName(),Integer.toHexString(t.hashCode()));
taskPuttersWaitSet.signal();
return t;
} finally {
lock.unlock();
}
}
// 添加任务
public void put(T task) {
lock.lock();
try {
while (queue.size() == taskQueueCapacity) {
try {
log.debug("任务:{}等待任务队列空位",Integer.toHexString(task.hashCode()));
taskPuttersWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.addLast(task);
log.debug("任务:{}已放入任务队列",Integer.toHexString(task.hashCode()));
taskGettersWaitSet.signal();
} finally {
lock.unlock();
}
}
public boolean putWithTimeOut(T task, long timeout, TimeUnit unit) {
lock.lock();
try {
long nanos = unit.toNanos(timeout);
while (queue.size() == taskQueueCapacity) {
try {
if(nanos <= 0) {
return false;
}
nanos = taskPuttersWaitSet.awaitNanos(nanos); // 返回剩余等待时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.addLast(task);
taskGettersWaitSet.signal();
return true;
} finally {
lock.unlock();
}
}
public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
lock.lock();
try {
if(queue.size() == taskQueueCapacity) {
rejectPolicy.reject(this, task);
} else {
queue.addLast(task);
log.debug("任务:{}已放入任务队列",Integer.toHexString(task.hashCode()));
taskGettersWaitSet.signal();
}
} finally {
lock.unlock();
}
}
}
05-19