参考大神作品:https://blog.csdn.net/z55887/article/details/79060070
import java.util.ArrayList;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.locks.ReentrantLock;
public class MyThreadPool {
//存放线程的集合
private ArrayList<MyThread> threads;
//任务队列
private ArrayBlockingQueue<Runnable> taskQueue;
//线程池初始化大小
private int threadNum;
//已经工作的线程池数目
private int workThreadNum;
private final ReentrantLock lock = new ReentrantLock();
//构造函数初始化线程池
public MyThreadPool(int threadNum) {
this.threadNum = threadNum;
threads = new ArrayList<MyThread>(threadNum);
taskQueue = new ArrayBlockingQueue<Runnable>(threadNum*4);
workThreadNum = 0;
}
//提交任务
public void execute(Runnable runnable){
try {
lock.lock();
//线程池未满
if(workThreadNum<threadNum){
MyThread myThread = new MyThread(runnable);
myThread.start();
threads.add(myThread);
workThreadNum++;
}else{//线程池已满,加入等待队列
if(!taskQueue.offer(runnable)){
//等待队列已满,拒绝任务
rejectTask();
}
}
} finally{
lock.unlock();
}
}
public void rejectTask(){
System.out.println("任务已满,无法执行");
}
public static void main(String[] args) {
MyThreadPool myThreadPool = new MyThreadPool(5);
Runnable task = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"执行中");
}
};
for (int i = 0; i < 20; i++) {
myThreadPool.execute(task);
}
}
public class MyThread extends Thread{
private Runnable task;
public MyThread(Runnable task){
this.task=task;
}
//一直启动,不断从任务队列中取任务出来做
public void run(){
while(true){
//初始化任务不为空
if(task!=null){
task.run();
task=null;
}else{
Runnable queueTask = taskQueue.poll();
if(queueTask!=null){
queueTask.run();
}
}
}
}
}
}
要点:
1、线程池有4个私有变量,线程集合、任务队列、工作的线程数量、线程池初始化大小
2、线程池中的线程一直处于执行状态,如果执行完一个任务回去任务队列中寻找任务来执行