原理:
- ThreadPool包含两大组件:BlockQueue和ThreadPool
- 线程达到上线之后,新进的任务都会进入BlockQueue
- 线程完成当前任务后会从BlockQueue中获取新的任务
package thread.pool;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class MyPool {
public static void main(String[] args) {
ThreadPool pool = new ThreadPool(2, 3, 1, new RejectPolicy<Runnable>() {
@Override
public void reject(BlockQueue<Runnable> queue, Runnable task) {
// 线程池忙,拒绝接收任务时的策略,可自定义
// 1,什么都不干
System.out.println("插入失败,什么都不干");
}
});
// 模拟加入10个任务
for (int i=0 ;i<10 ;i++) {
pool.execute(new Runnable() {
@Override
public void run() {
try {
System.out.println("task" + Thread.currentThread().getName());
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
}
@FunctionalInterface // 拒绝策略
interface RejectPolicy<T> {
void reject(BlockQueue<T> queue, T task);
}
class ThreadPool{
// 线程数
private int core;
// 等待加入队列的最大等待时间,超出时间结束线程或者告知调用者加入任务失败
private long timeOut;
private BlockQueue<Runnable> blockQueue;
private List<Work> workers = new ArrayList<>();
private RejectPolicy<Runnable> rejectPolicy;
public ThreadPool(int core, int queueSize, long timeOut) {
this.core = core;
blockQueue = new BlockQueue<>(queueSize);
this.timeOut = timeOut;
}
public ThreadPool(int core, int queueSize, long timeOut,RejectPolicy<Runnable> rejectPolicy) {
this.core = core;
blockQueue = new BlockQueue<>(queueSize);
this.rejectPolicy = rejectPolicy;
this.timeOut = timeOut;
}
public void execute(Runnable task) {
synchronized (workers) {
if (workers.size() < core) {
Work work = new Work(task);
workers.add(work);
work.start();
} else {
// blockQueue.put(task);
boolean success = blockQueue.offer(task, timeOut, TimeUnit.SECONDS);
if (!success) {
rejectPolicy.reject(blockQueue,task);
}
}
}
}
class Work extends Thread{
private Runnable task;
public Work(Runnable task) {
this.task = task;
}
@Override
public void run() {
while (task!=null ||(task=blockQueue.poll())!=null) {
try {
task.run();
}catch (Exception e) {
e.printStackTrace();
}finally {
task = null;
}
}
}
}
}
class BlockQueue<T> {
private volatile LinkedList<T> pool = new LinkedList<>();
private ReentrantLock lock = new ReentrantLock();
private Condition emptyCondition = lock.newCondition();
private Condition fullCondition = lock.newCondition();
private int queueSize;
public BlockQueue(int queueSize) {
this.queueSize = queueSize;
}
// 带超时时间阻塞添加
public boolean offer(T task, long timeout, TimeUnit timeUnit) {
lock.lock();
long nanos = timeUnit.toNanos(timeout);
try {
while (pool.size() == queueSize) {
if (nanos < 0) {
System.out.println("=====插入超时:" + task);
return false;
}
nanos = fullCondition.awaitNanos(nanos);
}
System.out.println("插入队列:" + task);
pool.add(task);
emptyCondition.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return true;
}
public void put(T task) {
lock.lock();
try {
while (pool.size() == queueSize) {
fullCondition.await();
}
System.out.println("插入队列:" + task);
pool.add(task);
emptyCondition.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public T poll() {
lock.lock();
try {
while (pool.size() == 0) {
try {
emptyCondition.await();
}catch (Exception e) {
e.printStackTrace();
}
}
T t = pool.removeFirst();
System.out.println("溢出队列:" + t);
fullCondition.signal();
return t;
} finally {
lock.unlock();
}
}
// 带超时阻塞获取
public T poll(long timeout, TimeUnit unit) {
lock.lock();
long nanos = unit.toNanos(timeout);
try {
while (pool.size() == 0) {
try {
if (nanos < 0) {
return null;
}
// 防止虚假唤醒
nanos = emptyCondition.awaitNanos(nanos);
}catch (Exception e) {
e.printStackTrace();
}
}
T t = pool.removeFirst();
System.out.println("溢出队列:" + t);
fullCondition.signal();
return t;
} finally {
lock.unlock();
}
}
}