简单线程池的实现
ThreadPool实现
package six;
import java.util.List;
import java.util.Vector;
public class ThreadPool {
private static ThreadPool instance = null;
//空闲的线程队列
private List<Worker> idleThreads;
//已有的线程队列
private int threadCount;
private boolean isShutDown = false;
private ThreadPool() {
this.idleThreads = new Vector<>(5);
threadCount = 0;
}
public int getCreatedThreadsCount() {
return threadCount;
}
//取得线程池实例
public synchronized static ThreadPool getInstance() {
if(instance == null)
instance = new ThreadPool();
return instance;
}
//将线程放入线程池中
protected synchronized void repool(Worker repoolingThread) {
if(!isShutDown) {
idleThreads.add(repoolingThread);
}else {
repoolingThread.shutDown(); //关闭线程
}
}
//停止线程池中的所有线程
public synchronized void shutdown() {
isShutDown = true;
for(int threadIndex = 0; threadIndex < idleThreads.size(); threadIndex++) {
Worker idleThread = (Worker)idleThreads.get(threadIndex);
idleThread.shutDown();
}
}
//执行任务
public synchronized void start(Runnable target) {
Worker thread = null;
//如果有空闲线程,直接使用
if(idleThreads.size() > 0) {
int lastIndex = idleThreads.size() - 1;
thread = (Worker)idleThreads.get(lastIndex);
idleThreads.remove(lastIndex);
//立即执行这个任务
thread.setTarget(target);
}else {
threadCount++;
//创建新的线程
thread = new Worker(target, "PThread #" + threadCount, this);
thread.start();
}
}
}
Worker实现
package six;
public class Worker extends Thread{
//线程池
private ThreadPool pool;
//任务
private Runnable target;
private boolean isShutDown = false;
private boolean isIdle = false;
public Worker(Runnable target, String name, ThreadPool pool) {
super(name);
this.pool = pool;
this.target = target;
}
public Runnable getTarget() {
return target;
}
public boolean isIdle() {
return isIdle;
}
public void run() {
while(!isShutDown) {
isIdle = false;
if(target != null) {
target.run();
}
//任务结束了
isIdle = true;
try
{
//该线程结束后,不关闭线程,而是放入线程池的空闲队列
pool.repool(this);
synchronized (this) {
//线程空闲,等待新的任务到来
wait();
}
}catch(InterruptedException ie) {
}
isIdle = false;
}
}
public void shutDown() {
isShutDown = true;
notifyAll();
}
public void setTarget(Runnable newtarget) {
target = newtarget;
//设置了任务之后,通知run()方法,开始执行这个任务
notifyAll();
}
}
线程池的种类
newFixedThreadPool:固定大小的线程池
newSingleThreadExexutor:单一线程的线程池
newCachedThreadPool:缓存的线程池
- ThreadPoolExecutor
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime, //存活时间
TimeUnit unit, //时间的单位
BlockingQueue<Runnable> workQueue) { //阻塞队列
//假如有10个线程,现在有第11个线程,于是将最新的一个放入workQueue
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
- newFixedThreadPool(通过ThreadPoolExecutor来构建线程池)
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
- newCachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
//这个队列容量是0,只起到交换数据的作用。
}
demo
package ThreadPool;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolDemo {
public static class MyTask implements Runnable{
@Override
public void run() {
System.out.println(System.currentTimeMillis() + ": Thread Id" + Thread.currentThread().getId());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyTask task = new MyTask();
ExecutorService es = Executors.newFixedThreadPool(3);
for(int i = 0; i < 10; i++) {
es.submit(task);
}
}
}