自己实现的线程池主要实现的功能
1.池内线程数控制在最小与最大值之间
2.根据任务数自动增加新线程并且延迟自动关闭多余的闲置线程
3.用栈管理任务实现新任务先处理
实现思路:设置死循环让线程无法结束并在线程池中获取新任务,无任务时则等待,有任务则执行。当加入新任务时唤醒等待线程/增加新线程来执行。并在线程池中统计线程个数来管理线程。
类中基本属性:
private static ThreadPool tp;
private final static int WAITTIME = 5000;//空闲线程最长等待时间
private final static int THREADPOOLMIN = 2;
private final static int THREADPOOLMAX = 4;
private ArrayList<Thread> threadList;// 当前线程数
private Stack<Runnable> workQueue;// 任务栈
public boolean isClosed;// 是否关闭线程池
private int threadPoolMaxSize;//最大线程数
private int threadPoolMinSize;//最小线程数
private int workThreadCount;// 工作线程数量
采用单例模式保证内存中只有一个线程池
private ThreadPool(int min, int max) {
if (min > max) {
throw new IllegalArgumentException("ThreadPool--create--min>max");
} else {
threadPoolMaxSize = max;
threadPoolMinSize = min;
threadList = new ArrayList<Thread>();
isClosed = false;
workThreadCount = 0;
workQueue = new Stack<Runnable>();
for (int i = 0; i < threadPoolMinSize; i++) {
addThread();
}
}
}
public static ThreadPool getInstance() {
return getInstance(THREADPOOLMIN, THREADPOOLMAX);
}
public static ThreadPool getInstance(int min, int max) {
if (tp == null) {
tp = new ThreadPool(min, max);
}
return tp;
}
判断及增加线程方法
private void addThread() {
WorkThread wt = new WorkThread();
workThreadCount++;
threadList.add(wt);
wt.start();
}
/**
* 是否能创建新线程 线程池没关闭&&没有空闲线程&&线程数量小于最大值&&剩余任务数不为空时增加新工作线程
*/
private synchronized boolean canCreateThread() {
return !isClosed&&threadList.size() == workThreadCount
&& threadList.size() < threadPoolMaxSize
&& !workQueue.empty();
}
/**
* 判断是否有多余线程
* @return
*/
private synchronized boolean hasOverThread() {
if (workQueue.empty() && threadList.size() > threadPoolMinSize) {
return true;
} else {
return false;
}
}
/**
* 关闭线程池
*/
public synchronized void close() {
isClosed = true;
workQueue.clear(); // 清空工作队列
notifyAll();
tp = null;
}
向池内添加任务,满足创建新线程条件则add线程,否则唤醒。
public synchronized void execute(Runnable task) {
if (isClosed) {
throw new IllegalStateException("ThreadPool is close");
}
workQueue.push(task);
if (canCreateThread()) {
addThread();
} else {
notify();
}
}
工作线程通过调用该方法来获取任务,当任务数为空时判断是否有多余工作线程,有则wait(WAITTIME)后自动唤醒再次判断达到延迟关闭多余线程的效果,否则直接wait等待外部唤醒
private synchronized Runnable getTask() {
boolean isWait = false;
while (workQueue.empty()) {
workThreadCount--;
if (isClosed)
return null;
try {
//有多余线程时wait(WAITTIME)后自动唤醒,延迟结束多余线程
if (hasOverThread()) {
if (isWait) {
return null;
} else {
isWait = true;
wait(WAITTIME);
}
} else {
wait();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
workThreadCount++;
}
Runnable runnable=workQueue.pop();
if (canCreateThread()) {
addThread();
}
return runnable;
}
工作线程类通过getTask()获取任务,当返回null时关闭自己,否则执行任务
private class WorkThread extends Thread {
@Override
public void run() {
// TODO Auto-generated method stub
Runnable task;
while (!isClosed) {
task = getTask();
if (task == null)
break;
task.run();
}
threadList.remove(WorkThread.this);
}
}
}