前幾天寫了一個固定大小的連接池,今天通過學習又整理一下線程池的實現邏輯,看完這片代碼,Java線程池的基本思想你就能完全hold住,離着高級程序員又近一步,歡迎大家參考和交流。
package com.smallfan.connectionpool;
import lombok.extern.slf4j.Slf4j;
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;
/**
* @PACKAGE_NAME: com.smallfan.connectionpool
* @NAME: TestThreadPool
* @USER: dell
* @DATE: 2020/5/29
* @PROJECT_NAME: aboutthread
*/
@Slf4j
public class TestThreadPool {
public static void main(String[] args) {
ThreadPool threadPool = new ThreadPool(1, 1000,
TimeUnit.MILLISECONDS, 1, ((queue, task) -> {
//死等
// queue.takeQueue();
//設置超時
// Object o = queue.takeQueueForTime(500, TimeUnit.MILLISECONDS);
//捨棄
// log.info("不干預,放棄 {}",task);
//拋出異常
// throw new RuntimeException("拋出異常"+task);
//交給主線程執行
task.run();
}));
for (int i = 0; i < 5; i++) {
int j = i;
threadPool.execute(() ->
{
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("執行第" + j);
}
);
}
}
}
@Slf4j
class ThreadPool {
//任務對列
private BlockingQueue<Runnable> taskQueue;
//線程集合
private HashSet workers = new HashSet<Worker>();
//線程數
private int threadSize;
//超時時間
private long timeout;
//時間單位
private TimeUnit timeUnit;
//拒絕策略
private RejectPolicy<Runnable> policy;
public ThreadPool(int threadSize, long timeout, TimeUnit timeUnit, int capacity, RejectPolicy<Runnable> policy) {
this.threadSize = threadSize;
this.timeout = timeout;
this.timeUnit = timeUnit;
taskQueue = new BlockingQueue<>(capacity);
this.policy = policy;
}
public void execute(Runnable task) {
synchronized (workers) {//公共資源保證線程安全
//如果任務數小於threadSize時直接執行
//否則加入到線程對列
if (workers.size() < threadSize) {
log.info("新增worker{}", task);
Worker worker = new Worker(task);
workers.add(worker);
worker.start();
} else {
//taskQueue.putQueue(task);
/**
* 考慮問題
* 1對列滿了死等
* 2設置超時時間
* 3捨棄
* 4主線程執行
* 5拋出異常
* 使用設計模式的策略模式解決
*/
taskQueue.tryPut(policy, task);
}
}
}
@FunctionalInterface
interface RejectPolicy<T> {
void reject(BlockingQueue<T> queue, T task);
}
class Worker extends Thread {
private Runnable runnable;
public Worker(Runnable runnable) {
this.runnable = runnable;
}
@Override
public void run() {
/**
* 執行任務
* 1.當runnable直接執行
* 2.當對列裏面存在任務時執行
*/
// while (runnable != null || (runnable = taskQueue.takeQueue()) != null) {
while (runnable != null || (runnable = taskQueue.takeQueueForTime(timeout, timeUnit)) != null) {
try {
log.info("執行worker{}", runnable);
runnable.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
runnable = null;//執行後置空
}
}
synchronized (workers) {
log.info("移除worker{}", this);
workers.remove(this);
}
}
}
}
//模擬阻塞隊列
@Slf4j
class BlockingQueue<T> {
//1.定義隊列大小
private int capacity;
//2.定義雙向鏈表,當做容器
private Deque<T> deque = new ArrayDeque<T>();
//3.定義鎖
private ReentrantLock lock = new ReentrantLock();
//4.定義空條件變量
private Condition emptyWaitSet = lock.newCondition();
//5.定義滿條件變量
private Condition fullWaitSet = lock.newCondition();
public BlockingQueue(int capacity) {
this.capacity = capacity;
}
//定義獲取方法
public T takeQueue() {
lock.lock();
try {
while (deque.isEmpty()) {//若還沒有
try {
emptyWaitSet.await();//空等待放入時喚醒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//若已經放入
T t = deque.removeFirst();
fullWaitSet.signal();//喚醒滿條件
return t;
} finally {
lock.unlock();//釋放鎖,避免死鎖
}
}
//定義超時獲取
public T takeQueueForTime(long timeout, TimeUnit unit) {
lock.lock();
long nanos = unit.toNanos(timeout);//統一時間單位
try {
while (deque.isEmpty()) {//若還沒有
try {
if (nanos <= 0) {
return null;
}
nanos = emptyWaitSet.awaitNanos(nanos);//防止虛假喚醒 使用等待時間減去消耗時間
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//若已經放入
T t = deque.removeFirst();
fullWaitSet.signal();//喚醒滿條件
return t;
} finally {
lock.unlock();//釋放鎖,避免死鎖
}
}
//定義放入方法
public void putQueue(T task) {
lock.lock();
try {
while (deque.size() == capacity) {//已經滿了
try {
fullWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
deque.addLast(task);
emptyWaitSet.signal();
log.info("加入隊列 {}", task);
} finally {
lock.unlock();
}
}
/**
* 任務多時,設置添加任務的超時時間
*
* @param task
* @param timeout
* @param timeUnit
* @return
*/
public boolean putQueueForTimeOut(T task, long timeout, TimeUnit timeUnit) {
lock.lock();
long nanos = timeUnit.toNanos(timeout);
try {
while (deque.size() == capacity) {//已經滿了
try {
if (nanos <= 0) {//添加失敗
return false;
}
nanos = fullWaitSet.awaitNanos(nanos);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
deque.addLast(task);
emptyWaitSet.signal();
return true;//添加成功
} finally {
lock.unlock();
}
}
//獲取容量
public int getCapacity() {
lock.lock();
try {
return deque.size();
} finally {
lock.unlock();
}
}
public void tryPut(ThreadPool.RejectPolicy<T> policy, T task) {
lock.lock();
try {
if (deque.size() == capacity) {//對列已滿 調用策略 讓調用者決定
policy.reject(this, task);
} else {//空閒
deque.addLast(task);
emptyWaitSet.signal();
}
} finally {
lock.unlock();
}
}
}