根据jdk自带的线程池实现一个简单的线程池,自己练手用,方便理解线程池工作原理。
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.ArrayList;
import java.util.List;
public class MyThreadPool {
private List<Thread> workers = new ArrayList<>();
private static BlockingQueue<Runnable> queue ;
public MyThreadPool(int coreSize, int queueSize){
queue = new ArrayBlockingQueue<Runnable>(queueSize);
for (int i =0;i<coreSize;i++){
Worker worker = new Worker(this);
worker.start();
workers.add(worker);
}
}
public Boolean submit(Runnable task){
return queue.offer(task );
}
static class Worker extends Thread{
private MyThreadPool threadPool;
public Worker(MyThreadPool threadPool) {
this.threadPool = threadPool;
}
@Override
public void run() {
while (true) {
try {
Runnable task = threadPool.queue.take();
task.run();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
MyThreadPool threadPool = new MyThreadPool(5, 10);
for (int i =0;i<5;i++){
Thread task = new Thread(i+"线程") {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"执行完毕");
};
};
threadPool.submit(task );
}
}
}
(未完待续)