@Slf4j(topic = "w.Test1")
public class Test1 {
public static void main(String[] args) {
ThreadPool pool = new ThreadPool(2, 1000, TimeUnit.MICROSECONDS, 10);
for (int i = 0; i < 5; i++) {
int j = i;
pool.execute(() -> log.debug("线程:{}在执行", j));
}
}
}
@Slf4j(topic = "w.Test1")
class ThreadPool {
// 任务队列
private BlockingQueue<Runnable> taskQueue;
// 线程集合
private HashSet<Worker> works = new HashSet<>();
// 核心线程数
private int coreSize;
// 超时时间
private long timeout;
// 时间单位
private TimeUnit timeUnit;
public ThreadPool(int coreSize, long timeout, TimeUnit timeUnit, int queueCapCity) {
this.coreSize = coreSize;
this.timeout = timeout;
this.timeUnit = timeUnit;
this.taskQueue = new BlockingQueue<>(queueCapCity);
}
// 执行任务
public void execute(Runnable task) {
synchronized (works) {
if (works.size() < coreSize) {
Worker worker = new Worker(task);
// 加入线程池
log.debug("加入核心线程");
works.add(worker);
worker.start();
} else {
taskQueue.pull(task);
}
}
}
class Worker extends Thread {
private Runnable task;
Worker(Runnable task) {
this.task = task;
}
@Override
public void run() {
while (task != null || (task = taskQueue.poll(timeout,timeUnit)) != null) {
try {
task.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
task = null;
}
}
synchronized (works) {
log.debug("移除该线程");
works.remove(this);
}
}
}
}
// 任务队列
@Slf4j(topic = "w.Test1")
class BlockingQueue<T> {
private Deque<T> queue = new ArrayDeque<>();
private ReentrantLock lock = new ReentrantLock();
// 生产者等待区
private Condition fullWaitSet = lock.newCondition();
// 消费者等到区
private Condition emptyWaitSet = lock.newCondition();
// 队列上限
private int capCity;
public BlockingQueue(int capCity) {
this.capCity = capCity;
}
// 获取永久等待方法
public T take() {
lock.lock();
try {
while (queue.isEmpty()) {
try {
log.debug("获取方法开始等待");
emptyWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T first = queue.removeFirst();
fullWaitSet.signal();
return first;
} finally {
lock.unlock();
}
}
// 获取带超时等待方法
public T poll(long timeout, TimeUnit unit) {
lock.lock();
try {
long nanos = unit.toNanos(timeout);
while (queue.isEmpty()) {
if (nanos <= 0) {
return null;
}
try {
nanos = emptyWaitSet.awaitNanos(nanos);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T first = queue.removeFirst();
fullWaitSet.signal();
return first;
} finally {
lock.unlock();
}
}
// 添加任务方法
public void pull(T element) {
lock.lock();
try {
while (queue.size() >= capCity) {
try {
log.debug("添加方法开始等待");
fullWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.addLast(element);
emptyWaitSet.signal();
} finally {
lock.unlock();
}
}
}
java--自定义线程池(1)
最新推荐文章于 2024-06-02 17:50:48 发布