UML
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/478b130d0742a4c8e2d6a9d0df63c898.png)
核心代码
任务队列满时执行的拒绝策略
- 枚举单例 + 策略(DenyPolicyStrategy.java)
package com.example.executor.service.impl;
import com.example.executor.exception.RunnableDenyException;
public enum DenyPolicyStrategy {
DISCARD_DENY_POLICY_STRATEGY((runnable, threadPool) -> {}),
ABORT_DENY_POLICY_STRATEGY((runnable, threadPool) -> {
throw new RunnableDenyException("The runnable " + runnable + " will be abort.");
}),
RUNNER_DENY_POLICY_STRATEGY((runnable, threadPool) -> {
if (!threadPool.isShutdown()) {
runnable.run();
}
});
public RejectFunction rejectFunction;
DenyPolicyStrategy(RejectFunction rejectFunction) {
this.rejectFunction = rejectFunction;
}
public void reject(Runnable runnable, ThreadPool threadPool) throws RunnableDenyException {
rejectFunction.reject(runnable, threadPool);
}
interface RejectFunction {
void reject(Runnable runnable, ThreadPool threadPool) throws RunnableDenyException;
}
}
核心线程池
- 使用Builer模式创建线程池
- 使用了一个核心线程维护线程池中的线程数量
- 关闭线程池时, 关闭其中维护的线程,并且将核心线程打断
- 创建线程时,将自己自定义的线程和jvm中的核心线程绑定,保存到栈中
package com.example.executor.service.impl;
import com.example.executor.exception.InitThreadPoolException;
import com.example.executor.exception.RunnableDenyException;
import com.example.executor.service.DenyPolicyStrategy;
import com.example.executor.service.RunnableQueue;
import com.example.executor.service.ThreadFactory;
import com.example.executor.service.ThreadPool;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class BasicThreadPool implements ThreadPool {
private final int initSize;
private final int maxSize;
private final int coreSize;
private int activeCount;
private final ThreadFactory threadFactory;
private final RunnableQueue runnableQueue;
private volatile boolean isShutdown;
private final LinkedList<ThreadTask> threadStack;
private final long keepAliveTime;
private final TimeUnit timeUnit;
private final Thread threadPoolCoreThread;
public BasicThreadPool(Builder builder) {
this.initSize = builder.initSize;
this.maxSize = builder.maxSize;
this.coreSize = builder.coreSize;
this.threadFactory = builder.threadFactory;
this.runnableQueue = new LinkedRunnableQueue(builder.queueSize, builder.denyPolicyStrategy, this);
this.keepAliveTime = builder.keepAliveTime;
this.timeUnit = builder.timeUnit;
this.threadStack = new LinkedList<>();
this.threadPoolCoreThread = new Thread(this::coreThreadRun);
this.isShutdown = false;
this.init();
}
private void init() {
for (int i = 0; i < initSize; i++) {
newThread();
}
this.threadPoolCoreThread.start();
}
private void newThread() {
InternalTask internalTask = new InternalTask(runnableQueue);
Thread thread = this.threadFactory.createThread(internalTask);
ThreadTask threadTask = new ThreadTask(thread, internalTask);
threadStack.offer(threadTask);
this.activeCount++;
thread.start();
}
private void removeThread() {
ThreadTask threadTask = threadStack.removeLast();
threadTask.internalTask.stop();
this.activeCount--;
}
public void coreThreadRun() {
while (!isShutdown && !this.threadPoolCoreThread.isInterrupted()) {
try {
timeUnit.sleep(keepAliveTime);
} catch (InterruptedException e) {
isShutdown = true;
break;
}
synchronized (this) {
if (isShutdown) {
break;
}
if (runnableQueue.size() > 0 && activeCount < coreSize) {
for (int i = initSize; i < coreSize; i++) {
newThread();
}
continue;
}
if (runnableQueue.size() > 0 && activeCount < maxSize) {
for (int i = coreSize; i < maxSize; i++) {
newThread();
}
}
if (runnableQueue.size() == 0 && activeCount > coreSize) {
for (int i = coreSize; i < activeCount; i++) {
removeThread();
}
}
}
}
}
@Override
public void execute(Runnable runnable) throws RunnableDenyException {
checkIsShutdown();
this.runnableQueue.offer(runnable);
}
@Override
public synchronized RunnableQueue shutdown() {
if (isShutdown) {
return null;
}
isShutdown = true;
threadStack.forEach(threadTask -> {
threadTask.internalTask.stop();
threadTask.thread.interrupt();
});
this.threadPoolCoreThread.interrupt();
return this.runnableQueue;
}
@Override
public int getInitSize() {
checkIsShutdown();
return this.initSize;
}
@Override
public int getMaxSize() {
checkIsShutdown();
return this.maxSize;
}
@Override
public int getCoreSize() {
checkIsShutdown();
return this.coreSize;
}
@Override
public int getQueueSize() {
checkIsShutdown();
return this.runnableQueue.size();
}
@Override
public synchronized int getActiveCount() {
return this.activeCount;
}
@Override
public boolean isShutdown() {
return this.isShutdown;
}
private void checkIsShutdown() {
if (isShutdown) {
throw new IllegalStateException("连接池已经被销毁");
}
}
private static class ThreadTask {
Thread thread;
InternalTask internalTask;
public ThreadTask(Thread thread, InternalTask internalTask) {
this.thread = thread;
this.internalTask = internalTask;
}
}
private static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger GROUP_COUNTER = new AtomicInteger(1);
private static final ThreadGroup threadGroup = new ThreadGroup("MyThreadPool-" + GROUP_COUNTER.getAndDecrement());
private static final AtomicInteger COUNTER = new AtomicInteger(0);
@Override
public Thread createThread(Runnable runnable) {
return new Thread(threadGroup, runnable, "thread-pool-" + COUNTER.getAndDecrement());
}
}
public static class Builder {
private int initSize = 2;
private int maxSize = 6;
private int coreSize = 4;
private int queueSize = 1000;
private DenyPolicyStrategy denyPolicyStrategy = DenyPolicyStrategy.DISCARD_DENY_POLICY_STRATEGY;
private ThreadFactory threadFactory = new DefaultThreadFactory();
private long keepAliveTime = 12;
private TimeUnit timeUnit = TimeUnit.SECONDS;
public BasicThreadPool build() throws InitThreadPoolException {
if (this.maxSize < this.initSize) {
throw new InitThreadPoolException("初始化线程数不能大于最大线程数");
}
if (this.coreSize < this.initSize) {
throw new InitThreadPoolException("初始化线程数不能大于核心线程数");
}
if (this.maxSize < this.coreSize) {
throw new InitThreadPoolException("核心线程数不能大于最大线程数");
}
return new BasicThreadPool(this);
}
public Builder setInitSize(int initSize) {
this.initSize = initSize;
return this;
}
public Builder setMaxSize(int maxSize) {
this.maxSize = maxSize;
return this;
}
public Builder setCoreSize(int coreSize) {
this.coreSize = coreSize;
return this;
}
public Builder setQueueSize(int queueSize) {
this.queueSize = queueSize;
return this;
}
public Builder setDenyPolicyStrategy(DenyPolicyStrategy denyPolicyStrategy) {
this.denyPolicyStrategy = denyPolicyStrategy;
return this;
}
public Builder setThreadFactory(ThreadFactory threadFactory) {
this.threadFactory = threadFactory;
return this;
}
public Builder setKeepAliveTime(long keepAliveTime) {
this.keepAliveTime = keepAliveTime;
return this;
}
public Builder setTimeUnit(TimeUnit timeUnit) {
this.timeUnit = timeUnit;
return this;
}
}
}
线程池中使用的任务模型
- 任务模型工作就是不断拿线程池中的队列中的任务执行, 如果队列为null时挂起
package com.example.executor.service.impl;
import com.example.executor.service.RunnableQueue;
public class InternalTask implements Runnable {
private final RunnableQueue runnableQueue;
private volatile boolean running = true;
public InternalTask(RunnableQueue runnableQueue) {
this.runnableQueue = runnableQueue;
}
@Override
public void run() {
while (running && !Thread.currentThread().isInterrupted()) {
Runnable task;
try {
task = runnableQueue.take();
} catch (InterruptedException e) {
this.running = false;
break;
}
task.run();
}
}
public void stop() {
this.running = false;
}
}
任务队列
package com.example.executor.service.impl;
import com.example.executor.exception.RunnableDenyException;
import com.example.executor.service.DenyPolicyStrategy;
import com.example.executor.service.RunnableQueue;
import com.example.executor.service.ThreadPool;
import java.util.LinkedList;
public class LinkedRunnableQueue implements RunnableQueue {
private final int limit;
private final DenyPolicyStrategy denyPolicyStrategy;
private final LinkedList<Runnable> runnableLinkedList = new LinkedList();
private final ThreadPool threadPool;
public LinkedRunnableQueue(int limit, DenyPolicyStrategy denyPolicyStrategy, ThreadPool threadPool) {
this.limit = limit;
this.denyPolicyStrategy = denyPolicyStrategy;
this.threadPool = threadPool;
}
@Override
public void offer(Runnable runnable) throws RunnableDenyException {
synchronized (runnableLinkedList) {
if (runnableLinkedList.size() >= limit) {
denyPolicyStrategy.reject(runnable, threadPool);
} else {
runnableLinkedList.add(runnable);
runnableLinkedList.notifyAll();
}
}
}
@Override
public Runnable take() throws InterruptedException {
synchronized (runnableLinkedList) {
while (runnableLinkedList.isEmpty()) {
try {
runnableLinkedList.wait();
} catch (InterruptedException e) {
throw e;
}
}
}
return runnableLinkedList.removeFirst();
}
@Override
public int size() {
synchronized (runnableLinkedList) {
return runnableLinkedList.size();
}
}
}
其他一些接口的定义
- 一些抛出的异常
package com.example.executor.exception;
public class InitThreadPoolException extends Exception {
public InitThreadPoolException(String message) {
super(message);
}
}
package com.example.executor.exception;
import com.example.executor.service.DenyPolicyStrategy;
public class RunnableDenyException extends Exception {
public RunnableDenyException(String message) {
super(message);
}
}
- ThreadPool线程池
package com.example.executor.service;
import com.example.executor.exception.RunnableDenyException;
public interface ThreadPool {
void execute(Runnable runnable) throws RunnableDenyException;
RunnableQueue shutdown();
int getInitSize();
int getMaxSize();
int getCoreSize();
int getQueueSize();
int getActiveCount();
boolean isShutdown();
}
- 线程工厂定义(创建jvm线程, 构造组,线程名)
package com.example.executor.service;
@FunctionalInterface
public interface ThreadFactory {
Thread createThread(Runnable runnable);
}
- 任务队列接口
package com.example.executor.service;
import com.example.executor.exception.RunnableDenyException;
public interface RunnableQueue {
void offer(Runnable runnable) throws RunnableDenyException;
Runnable take() throws InterruptedException;
int size();
}
- 测试Demo
package com.example.executor;
import com.example.executor.exception.InitThreadPoolException;
import com.example.executor.service.ThreadPool;
import com.example.executor.service.impl.BasicThreadPool;
import java.util.concurrent.TimeUnit;
public class Demo {
public static void main(String[] args) {
ThreadPool threadPool;
try {
threadPool = new BasicThreadPool.Builder()
.setInitSize(2)
.setCoreSize(4)
.setMaxSize(6)
.build();
} catch (InitThreadPoolException e) {
e.printStackTrace();
return;
}
try {
for (int i = 0; i < 20; i++) {
threadPool.execute(() -> {
try {
TimeUnit.SECONDS.sleep(10);
System.out.println(Thread.currentThread().getName() + " is running and done.");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
for (; ; ) {
System.out.println("activeCount: " + threadPool.getActiveCount());
System.out.println("queueSize: " + threadPool.getQueueSize());
System.out.println("coreSize: " + threadPool.getCoreSize());
System.out.println("maxSize: " + threadPool.getMaxSize());
System.out.println("========================");
TimeUnit.SECONDS.sleep(5);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
全部代码
全部代码