上一篇文章我们定义了相关的接口和异常类,接下来我们将逐一具体实现这些接口
实现任务队列接口
package myThreadPool;
import java.util.LinkedList;
/**
* @ClassName LinkedRunnableQueue
* @Description 任务队列实现类
* @Author zhang
* @Date 2020/2/19 0:09
* @Version 1.0
**/
public class LinkedRunnableQueue implements RunnableQueue{
//任务队列的最大容量,在构造时传入
private final int limit;
//如果队列满了,采取的拒绝策略
private final DenyPolicy denyPolicy;
//存放任务的队列
private final LinkedList<Runnable> runnableList=new LinkedList<>();
private final ThreadPool threadPool;
public LinkedRunnableQueue(int limit, DenyPolicy denyPolicy, ThreadPool threadPool) {
this.limit = limit;
this.denyPolicy = denyPolicy;
this.threadPool = threadPool;
}
@Override
public void offer(Runnable runnable) {
synchronized (runnableList){
if(runnableList.size()>=limit){
//无法容纳新的任务时,拒绝策略
denyPolicy.reject(runnable,threadPool);
}else{
//将任务加到队尾,并唤醒阻塞中的线程
runnableList.addLast(runnable);
runnableList.notifyAll();
}
}
}
@Override
public Runnable take() throws InterruptedException{
synchronized (runnableList){
while(runnableList.isEmpty()){
try {
//如果任务队列中没有任务,则当前线程会被挂起,进入runnableList关联的monitor waitset中等待被唤醒(新的任务的加入)
runnableList.wait();
} catch (InterruptedException e) {
//被中断时异常处理,可以抛出
throw e;
}
}
//移除任务头部第一个任务
return runnableList.removeFirst();
}
}
@Override
public int size() {
synchronized (runnableList){
//返回当前任务队列的任务个数
return runnableList.size();
}
}
}
线程池代码
package myThreadPool;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @ClassName BasicThreadPool
* @Description 具体线程池实现
* @Author zhang
* @Date 2020/2/22 23:30
* @Version 1.0
**/
public class BasicThreadPool extends Thread 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;
//线程池是否已经被shutdown
private volatile boolean isShutdown=false;
//工作线程队列
private final Queue<ThreadTask> threadQueue=new ArrayDeque<>();
//默认拒绝策略:直接丢弃任务
private final static DenyPolicy DEFAULT_DENY_POLICY=new DenyPolicy.DiscardDenyPolicy();
//默认线程工厂
private final static ThreadFactory DEFAULT_THREAD_FACTORY=new DeFaultThreadFactory();
private final long keepAliveTime;
private final TimeUnit timeUnit;
public BasicThreadPool(int initSize, int maxSize, int coreSize,int queueSize) {
this(initSize,maxSize,coreSize,DEFAULT_THREAD_FACTORY,queueSize,DEFAULT_DENY_POLICY,10,TimeUnit.SECONDS);
}
public BasicThreadPool(int initSize, int maxSize, int coreSize,
ThreadFactory threadFactory, int queueSize,
DenyPolicy denyPolicy, long keepAliveTime,
TimeUnit timeUnit) {
this.initSize = initSize;
this.maxSize = maxSize;
this.coreSize = coreSize;
this.threadFactory = threadFactory;
this.runnableQueue =new LinkedRunnableQueue(queueSize,denyPolicy,this);
this.keepAliveTime = keepAliveTime;
this.timeUnit = timeUnit;
this.init();
}
//ThreadTask只是InternalTask和Thread的一个组合
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 group=new ThreadGroup("MyThreadPool1-"+GROUP_COUNTER.getAndDecrement());
private static final AtomicInteger COUNTER=new AtomicInteger(0);
@Override
public Thread createThread(Runnable runnable) {
return new Thread(group,runnable,"thread-pool-"+COUNTER.getAndDecrement());
}
}
//初始化,先创建initSize个线程
private void init(){
start();
for(int i=0;i<initSize;i++){
newThread();
}
}
private void newThread(){
//创建任务线程,并且启动
InternalTask internalTask=new InternalTask(runnableQueue);
Thread thread=this.threadFactory.createThread(internalTask);
ThreadTask threadTask=new ThreadTask(thread,internalTask);
threadQueue.offer(threadTask);
this.activeCount++;
thread.start();
}
private void removeThread(){
//从线程池中移除某个线程 这里移除队列中第一个线程
ThreadTask threadTask=threadQueue.remove();
threadTask.internalTask.stop();
this.activeCount--;
}
@Override
public void run() {
while(!isShutdown&&!isInterrupted()){
try{
//每个keepAliveTime就自动维护活动线程状态
timeUnit.sleep(keepAliveTime);
}catch (InterruptedException e){
isShutdown=true;
break;
}
synchronized (this){
if(isShutdown)
break;
//当前任务队列中有任务尚未处理,并且activeCount<coreSize则继续扩容
if(runnableQueue.size()>0&&activeCount<coreSize){
for(int i=coreSize;i<maxSize;i++){
newThread();
}
}
//如果任务队列中没有任务处理,则需要挥手,回收至coreSize即可
if(runnableQueue.size()==0&&activeCount>coreSize){
for(int i=coreSize;i<activeCount;i++){
removeThread();
}
}
}
}
}
@Override
public void execute(Runnable runnable) {
if(this.isShutdown){
throw new IllegalStateException("this threadpool is distroy");
}
//提交任务只是简单的往任务队列中插入runnable
this.runnableQueue.offer(runnable);
}
@Override
public void shutdown() {
synchronized (this){
if(isShutdown)
return;
isShutdown=true;
threadQueue.forEach(threadTask -> {
threadTask.internalTask.stop();
threadTask.thread.interrupt();
});
this.interrupt();
}
}
@Override
public int getInitSize() {
if(isShutdown)
throw new IllegalStateException("The threadpool is destroy");
return this.initSize;
}
@Override
public int getMaxSize() {
if(isShutdown)
throw new IllegalStateException("The threadpool is destroy");
return this.maxSize;
}
@Override
public int getCoreSize() {
if(isShutdown)
throw new IllegalStateException("The threadpool is destroy");
return this.coreSize;
}
@Override
public int getQueueSize() {
if(isShutdown)
throw new IllegalStateException("The threadpool is destroy");
return this.runnableQueue.size();
}
@Override
public int getActiveCount() {
if(isShutdown)
throw new IllegalStateException("The threadpool is destroy");
return this.activeCount;
}
@Override
public boolean isShutdown() {
return this.isShutdown;
}
}
感兴趣的小伙伴可以自己测试一下,这里不贴测试代码啦