class ThreadPool {
//任务队列
private BlockQueue<Runnable> taskQueue;
//线程数量,用来指定线程集合的最大个数
private int coreSize;
// 线程集合
private List<Worker> workers = new Vector<>();
//线程等待时间
private long takeTime;
//线程等待时间单位
private TimeUnit takeTimeUnit;
public ThreadPool (int coreSize, int taskQueueCapacity,long takeTime, TimeUnit takeTimeUnit) {
this.taskQueue = new BlockQueue<>(taskQueueCapacity);
this.coreSize = coreSize;
this.takeTime = takeTime;
this.takeTimeUnit = takeTimeUnit;
}
/**
* 任务执行方法
* @param task
*/
public void execute(Runnable task) {
synchronized (workers) {
//如果线程集合中的线程数量小于指定线程数量就新建线程,并添加到线程集合中
//否则就将任务尝试添加到任务队列中去.如果任务队列已经满了,哪个指定处理策略
if (workers.size() < coreSize) {
Worker worker = new Worker(task);
workers.add(worker);
worker.start();
} else {
taskQueue.tryPut(task, (blockQueue, t) -> {
task.run();
});
}
}
}
class Worker extends Thread {
Runnable task;
public Worker(Runnable task) {
this.task = task;
}
@Override
public void run() {
//一个任务执行完之后就会尝试从任务队列里去任务
while (task != null || (task = taskQueue.take(takeTime, takeTimeUnit)) != null) {
try {
//Thread.sleep(1000);
task.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
task = null;
}
}
synchronized (workers) {
workers.remove(this);
}
}
}
}
class BlockQueue<T> {
private Deque<T> queue = new ArrayDeque<T>();
private ReentrantLock lock = new ReentrantLock();
//当任务队列已经满了的条件
private Condition fullWaitSet = lock.newCondition();
//当任务队列为空的条件
private Condition emptyWaitSet = lock.newCondition();
//任务队列的容量
private int capacity;
public BlockQueue(int capacity) {
this.capacity = capacity;
}
public T take() {
lock.lock();
try {
while (queue.isEmpty()) {
try {
emptyWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
fullWaitSet.signal();
return queue.removeFirst();
} finally {
lock.unlock();
}
}
public T take(long time, TimeUnit timeUnit) {
long nanos = timeUnit.toNanos(time);
lock.lock();
try {
while (queue.isEmpty()) {
try {
if (nanos <= 0) {
return null;
}
nanos = emptyWaitSet.awaitNanos(nanos);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
fullWaitSet.signal();
return queue.removeFirst();
} finally {
lock.unlock();
}
}
public void tryPut(T t, BiConsumer<BlockQueue<T>, T> consumer) {
lock.lock();
try {
if (queue.size() < capacity) {
queue.addLast(t);
emptyWaitSet.signal();
} else {
consumer.accept(this, t);
}
} finally {
lock.unlock();
}
}
public void put(T t) {
System.out.println(queue.size());
lock.lock();
try {
while (queue.size() == capacity) {
try {
fullWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.addLast(t);
} finally {
lock.unlock();
}
}
}
自定义一个简易的java线程池
最新推荐文章于 2024-09-03 20:17:53 发布