-
ThreadPool
:线程池主体
BlockingQueue<Runnable> taskQueue
:任务阻塞队列HashSet<Worker> workers
:工作线程集合coreSize
:核心线程数timeout
+ timeUnit
:线程空闲超时时间(当前未实现)
-
Worker
:工作线程(内部类)
-
BlockingQueue<T>
:自定义阻塞队列
- 基于
ReentrantLock
和Condition
实现生产-消费模型
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;
public class TestPool {
public static void main(String[] args) {
ThreadPool threadPool =
new ThreadPool(TimeUnit.MILLISECONDS,1000,2,10);
for (int i = 0; i < 5; i++) {
int j = i;
threadPool.execute(()->{
System.out.println(j);
});
}
}
}
class ThreadPool{
private BlockingQueue<Runnable> taskQueue;
private HashSet<Worker> workers = new HashSet();
private int coreSize;
private long timeout;
private TimeUnit timeUnit;
public void execute(Runnable task){
synchronized (workers){
if(workers.size()<coreSize){
Worker worker = new Worker(task);
workers.add(worker);
worker.start();
}else {
taskQueue.put(task);
}
}
}
public ThreadPool(TimeUnit timeUnit, long timeout, int coreSize,int queueCapacity) {
this.timeUnit = timeUnit;
this.timeout = timeout;
this.coreSize = coreSize;
this.taskQueue = new BlockingQueue<>(queueCapacity);
}
class Worker extends Thread{
private Runnable task;
public Worker(Runnable task) {
this.task = task;
}
@Override
public void run() {
while (task!=null || (task=taskQueue.take())!=null){
try {
task.run();
}catch (Exception e){
e.printStackTrace();
}finally {
task=null;
}
}
synchronized (workers){
workers.remove(this);
}
}
}
}
class BlockingQueue<T>{
private Deque<T> queue = new ArrayDeque<>();
private ReentrantLock lock = new ReentrantLock();
private Condition consumer = lock.newCondition();
private Condition product = lock.newCondition();
private int capacity;
public BlockingQueue(int capacity) {
this.capacity = capacity;
}
public T poll(long timeout, TimeUnit unit){
lock.lock();
try {
long nanos = unit.toNanos(timeout);
while (queue.isEmpty()){
try {
if(nanos <= 0){
return null;
}
nanos = consumer.awaitNanos(nanos);
}catch (InterruptedException e){
e.printStackTrace();
}
}
T t = queue.removeFirst();
product.signal();
return t;
}finally {
lock.unlock();
}
}
public T take(){
lock.lock();
try {
while (queue.isEmpty()){
try {
consumer.await();
}catch (InterruptedException e){
e.printStackTrace();
}
}
T t = queue.removeFirst();
product.signal();
return t;
}finally {
lock.unlock();
}
}
public void put(T element){
lock.lock();
try {
while (queue.size() == capacity){
try {
product.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.addLast(element);
consumer.signal();
}finally {
lock.unlock();
}
}
public int size(){
lock.lock();
try {
return queue.size();
}finally {
lock.unlock();
}
}
}