实现个简单的线程池

1 可以手动实现一个最简单的线程池,不考虑性能和等待机制等。
public class Worker extends Thread {

private LkThreadPool pool;
private Runnable target;
private boolean isShutDown=false;


public Worker(Runnable target,LkThreadPool pool){
this.pool=pool;
this.target=target;
}

public synchronized void setTarget(Runnable newTarget){
target=newTarget;
notifyAll();
}

public synchronized void run(){
while (!isShutDown){
System.out.println(Thread.currentThread()+" 开始执行");
if(target!=null){
//执行
target.run();
}

pool.repool(this);
System.out.println(Thread.currentThread()+" 执行完毕 回收");
synchronized (this){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public synchronized void shutDown(){
isShutDown=false;

notifyAll();
}

}

public class LkThreadPool {

private LinkedBlockingQueue<Worker> threadList ;

private boolean isShutDown=false;

private int threadCount=0;

public LkThreadPool(int threadSize){
if(threadSize>0){
threadList= new LinkedBlockingQueue<Worker>(threadSize);
}

}

//用完的线程返回线程池
public synchronized void repool(Worker worker){
try {
threadList.put(worker);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public synchronized void start(Runnable target){
if(threadList.size()>0){
//有空闲线程
Worker worker=threadList.poll();
worker.setTarget(target);
}else{
Worker worker=new Worker(target,this);
worker.start();
}
}

public synchronized void shutdown(){
isShutDown=true;
for(Worker worker:threadList){
worker.shutDown();
}

}

}
原文地址:https://www.cnblogs.com/lkdirk/p/6627749.html