1、线程池
1、自定义线程池
步骤1:自定义拒绝策略
@FunctionalInterface
public interface RejectPolicy<T> {
void reject(BlockingQueue<T> queue, T task);
}
步骤2:自定义任务队列
@Slf4j(topic = "c.BlockingQueue")
public class BlockingQueue<T> {
// 1.任务队列
private Deque<T> queue = new ArrayDeque<>();
// 2.锁
private ReentrantLock lock = new ReentrantLock();
// 3.生产者条件变量
private Condition producerWaitSet = lock.newCondition();
// 4.消费者条件变量
private Condition consumerWaitSet = lock.newCondition();
// 5.容量
int capacity;
public BlockingQueue(int capacity) {
this.capacity = capacity;
}
/**
* 阻塞添加
*
* @param task
*/
public void put(T task) {
lock.lock();
try {
if (queue.size() == capacity) {
try {
log.debug("等待加入任务队列{}", task);
producerWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.debug("任务加入队列{}", task);
queue.addLast(task);
consumerWaitSet.signal();
} finally {
lock.unlock();
}
}
/**
* 带超时时间的阻塞添加
*
* @param task
*/
public boolean put(T task, long timeout, TimeUnit timeUnit) {
lock.lock();
try {
long nanos = timeUnit.toNanos(timeout);
while (queue.size() == capacity) {
try {
if (nanos <= 0) {
log.debug("加入队伍超时{}", task);
return false;
}
log.debug("等待加入任务队列{}", task);
nanos = producerWaitSet.awaitNanos(nanos);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.debug("任务加入队列{}", task);
queue.addLast(task);
consumerWaitSet.signal();
return true;
} finally {
lock.unlock();
}
}
/**
* 阻塞获取任务
*
* @return
*/
public T get() {
lock.lock();
try {
// 防止唤醒之后没抢到又是空
while (queue.isEmpty()) {
try {
consumerWaitSet.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T t = queue.removeFirst();
log.debug("取到任务{}", t);
producerWaitSet.signal();
return t;
} finally {
lock.unlock();
}
}
/**
* 带超时时间的阻塞获取
*
* @return
*/
public T get(long timeout, TimeUnit timeUnit) {
lock.lock();
try {
long nanos = timeUnit.toNanos(timeout);
// 防止唤醒之后没抢到又是空
while (queue.isEmpty()) {
try {
if (nanos <= 0) {
log.debug("获取任务超时");
return null;
}
nanos = consumerWaitSet.awaitNanos(nanos);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T t = queue.removeFirst();
log.debug("取到任务{}", t);
producerWaitSet.signal();
return t;
} finally {
lock.unlock();
}
}
public int size() {
lock.lock();
try {
return queue.size();
} finally {
lock.unlock();
}
}
public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
lock.lock();
try {
if (queue.size() == capacity) {
rejectPolicy.reject(this, task);
} else {
log.debug("加入任务队列", task);
queue.addLast(task);
consumerWaitSet.signal();
}
} finally {
lock.unlock();
}
}
}
步骤3:自定义线程池
@Slf4j(topic = "c.ThreadPool")
public class ThreadPool {
// 任务队列
private BlockingQueue<Runnable> taskQueue;
// 线程集合
private final Set<Worker> workers = new HashSet<>();
// 核心线程数
private int coreSize;
// 获取任务的超时时间
private long timeout;
private TimeUnit timeUnit;
private RejectPolicy<Runnable> rejectPolicy;
public ThreadPool(int capacity, int coreSize, long timeout, TimeUnit timeUnit, RejectPolicy<Runnable> rejectPolicy) {
this.taskQueue = new BlockingQueue<>(1);
this.coreSize = coreSize;
this.timeout = timeout;
this.timeUnit = timeUnit;
this.rejectPolicy = rejectPolicy;
}
public void execute(Runnable task) {
// 当任务数量没有超过核心线程数,直接交给workers执行
// 反之,加入任务队列暂存
synchronized (workers) {
if (workers.size() < coreSize) {
Worker worker = new Worker(task);
log.debug("新增worker {}", worker);
workers.add(worker);
worker.start();
} else {
taskQueue.tryPut(rejectPolicy, task);
}
}
}
class Worker extends Thread {
private Runnable task;
public Worker(Runnable task) {
this.task = task;
}
@Override
public void run() {
// 执行任务
// 1. task 不为空,执行任务
// 2. task 执行完毕,接着从队列获取任务并执行
while (task != null || (task = taskQueue.get(timeout, timeUnit)) != null) {
try {
log.debug("执行任务{}", task);
task.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
task = null;
}
}
synchronized (workers) {
log.debug("worker被移除{}", this);
workers.remove(this);
}
}
}
}
步骤4:测试
public static void main(String[] args) {
ThreadPool threadPool = new ThreadPool(1, 1, 1, TimeUnit.SECONDS, (queue, task) -> {
// 1、死等
queue.put(task);
// 2、带超时等待
// queue.put(task, 1500, TimeUnit.MILLISECONDS);
// 3、让调用者放弃任务执行
// log.debug("放弃{}", task);
// 4、让调用者抛出异常
// throw new RuntimeException("任务执行失败" + task);
// 5、让调用者自己执行
// task.run();
});
threadPool.execute(() -> {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("{}", 11111);
});
for (int i = 0; i < 4; i++) {
int j = i;
new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadPool.execute(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("{}", j);
});
}).start();
}
}