根据线程池的原理,自己实现个线程池。
/*
* 线程池管理器:用于创建并管理线程池,包括: 创建线程池,销毁线程池,添加新任务
* 客户端等待一个可用线程、将任务传递给该线程以便执行、然后在任务完成时将线程归还给池
*/
public class ThreadPool {
private static ThreadPool instance = null;
private List<WorkerThread> idleWorkers;//空闲的线程队列
private int threadCounter;//已启动的线程总数
private boolean isShutDown = false;
public ThreadPool(){
this.idleWorkers = new Vector(10);
for (int i = 0; i < 10; i++) {
WorkerThread wk = new WorkerThread(this,new Task(String.valueOf(i)),"WorkerThread #"+String.valueOf(i));
idleWorkers.add(wk);
}
this.threadCounter = 10;
}
public synchronized static ThreadPool getInstance(){
if(instance==null){
instance = new ThreadPool();
}
return instance;
}
public synchronized void start(Runnable target){
if(idleWorkers.size()>0){//如果有空闲线程,取一个,给此空闲线程分配一个任务
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~idleWorkers.size()="+idleWorkers.size());
WorkerThread idleThread = idleWorkers.remove(idleWorkers.size()-1);
idleThread.setTarget(target);
}else{//如果没有空闲线程,新建一个空闲线程IdleThread,执行IdleThread.start
threadCounter++;
WorkerThread idleThread = new WorkerThread(this,target,"WorkerThread #"+threadCounter);
idleThread.start();
}
}
public void repool(WorkerThread workerThread){
idleWorkers.add(workerThread);
}
public void shutDown(){
this.isShutDown = true;
//关闭线程池中所有线程
for(WorkerThread workerThread:idleWorkers){
workerThread.shutDown();
}
}
public int getThreadCounter(){
return threadCounter;
}
}
/*
* 工作线程:线程池中线程,在没有任务时处于等待状态,以循环的方式执行任务
*/
public class WorkerThread extends Thread{
private ThreadPool threadPool;
private Runnable target;
private boolean isShutDown = false;
private boolean isIdle = true;
public WorkerThread(ThreadPool threadPool,Runnable target,String name){
super(name);
this.threadPool = threadPool;
this.target = target;
}
public synchronized void setTarget(Runnable target){
this.target = target;
notify();
}
public void run() {
while(!isShutDown){
System.out.println("workerThread run() ="+Thread.currentThread().getName());
//执行
isIdle = false;
target.run();
try {
isIdle = true;
threadPool.repool(this);
synchronized(this){
wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void shutDown(){
this.isShutDown = true;
notifyAll();
}
}
public class Task implements Runnable{
private String name;
public Task(){}
public Task(String name){
this.name = name;
}
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
System.out.println("main method");
for (int i = 0; i < 1000; i++) {
ThreadPool.getInstance().start(new Task("testThreadPool_"+String.valueOf(i)));
}
System.out.println("threadCounter="+ThreadPool.getInstance().getThreadCounter());
}
}