- 浏览: 13825 次
- 性别:
- 来自: 西安
最新评论
/**
* 一个线程池包括以下四个基本组成部分:
1、线程池管理器(ThreadPool):用于创建并管理线程池,包括 创建线程池,销毁线程池,添加新任务;
2、工作线程(PoolWorker):线程池中线程,在没有任务时处于等待状态,可以循环的执行任务;
3、任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行,
它主要规定了任务的入口,任务执行完后的收尾工作,任务的执行状态等;
4、任务队列(taskQueue):用于存放没有处理的任务。提供一种缓冲机制。
*/
package threadpoolmanager;
import java.util.Vector;
import threadpoolmanager.MonitorRunnable;
/**
* 线程池管理器
* @author Administrator
*
*/
public class ThreadPoolManager {
public static final int MAX_THREADS=200; //最大线程数
public static final int MAX_SPARE_THREADS=50; //最大空闲线程数
public static final int MIN_SPARE_THREADS=10; //最小空闲线程数
private Vector<WorkThread> pool; //工作线程队列
private MonitorRunnable monitor; // 监控线程内部类全局变量
private int maxThreads;
private int minSpareThreads;
private int maxSpareThreads;
private int currentThreadCount; //当前线程数量
private int currentThreadsBusy; //当前繁忙线程的数量
private boolean stopThePool; //关闭线程池的标志
/*
* 初始化线程池
*/
public ThreadPoolManager() {
maxThreads = MAX_THREADS;
maxSpareThreads = MAX_SPARE_THREADS;
minSpareThreads = MIN_SPARE_THREADS;
//默认当前线程、当前繁忙线程、线程池关闭标识分别为0、0、false
currentThreadCount = 0;
currentThreadsBusy = 0;
stopThePool = false;
}
public synchronized void start(){
//计算最大空闲线程和最小空闲线程
adjustLimits();
openThreads(minSpareThreads);
//启动监控线程,程序开始运行
monitor=new MonitorRunnable(this);
}
/*
* 这个方法给外部调用,把具体的任务传进来。
* 从这个方法可以看到,它实际上是把任务接过来,判断当前线程有多少,有空闲的就到池里面去取,
* 实际上是调用池里面的WorkThread线程来干活
*/
public synchronized void runIt(Task task){
if(task==null){
throw new NullPointerException("任务为空");
}
if(currentThreadCount==0||stopThePool){
throw new IllegalStateException("没有线程在运行");
}
WorkThread thread=null;
synchronized (this) {
if(currentThreadCount==currentThreadsBusy){
if(currentThreadCount<maxThreads){
int toOpen=currentThreadCount+minSpareThreads;
openThreads(toOpen);
}else{
while(currentThreadCount==currentThreadsBusy){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(currentThreadCount==0||stopThePool){
throw new IllegalStateException("没有线程在运行");
}
}
}
}
// 找到pool里最末端的一个线程。然后从pool里除去,currentThreadsBusy加1,表示忙的线程多一个了。
thread=pool.lastElement();
pool.removeElement(thread);
currentThreadsBusy++;
}
// 上面从pool里取出来线程了ControlRunnable,调用它的runIt方法,开始运行
thread.runIt(task);
}
/*
* 检测线程数量
* 如果当前线程个数 - 正在繁忙的线程 比 最大空闲线程数大,释放多余的空闲线程
*/
public synchronized void checkSpareThreads(){
if(stopThePool){
return;
}
if(currentThreadCount-currentThreadsBusy>maxSpareThreads){
int toFree=currentThreadCount-currentThreadsBusy-maxSpareThreads;
for(int i=0;i<toFree;i++){
WorkThread thread=pool.firstElement();
pool.removeElement(thread);
thread.shutdown();
currentThreadCount--;
}
}
}
/*
* 关闭线程池
*/
public synchronized void shutdown(){
if(!stopThePool){
stopThePool=true;
monitor.shutdown();
monitor=null;
for(int i=0;i<(currentThreadCount-currentThreadsBusy);i++){
WorkThread thread=pool.elementAt(i);
thread.shutdown();
}
currentThreadCount=currentThreadsBusy=0;
pool=null;
notifyAll();
}
}
/*
* 回收工作线程
*/
public synchronized void returnWorkThread(WorkThread work){
if(currentThreadCount==0||stopThePool){
work.shutdown();
return;
}
currentThreadsBusy--;
pool.addElement(work);
}
/*
* 计算最大空闲线程和最小空闲线程
*/
private void adjustLimits(){
if (maxThreads <= 0) {
maxThreads = MAX_THREADS;
}
if (maxSpareThreads >= maxThreads) {
maxSpareThreads = maxThreads;
}
if (maxSpareThreads <= 0) {
if (1 == maxThreads) {
maxSpareThreads = 1;
} else {
maxSpareThreads = maxThreads / 2;
}
}
if (minSpareThreads > maxSpareThreads) {
minSpareThreads = maxSpareThreads;
}
if (minSpareThreads <= 0) {
if (1 == maxSpareThreads) {
minSpareThreads = 1;
} else {
minSpareThreads = maxSpareThreads / 2;
}
}
}
/*
* 创建线程池
*/
private void openThreads(int toOpen){
if(toOpen>maxThreads){
toOpen=maxThreads;
}
if(0==currentThreadCount){
// 初始开minSpareThreads 10个元素
pool=new Vector<WorkThread>(toOpen);
}
for(int i=currentThreadCount;i<toOpen;i++){
WorkThread thread=new WorkThread(this);
pool.addElement(thread);
}
currentThreadCount=toOpen; //当前线程个数
}
/**
* @return the pool
*/
public Vector<WorkThread> getPool() {
return pool;
}
/**
* @param pool the pool to set
*/
public void setPool(Vector<WorkThread> pool) {
this.pool = pool;
}
/**
* @return the maxThreads
*/
public int getMaxThreads() {
return maxThreads;
}
/**
* @param maxThreads the maxThreads to set
*/
public void setMaxThreads(int maxThreads) {
this.maxThreads = maxThreads;
}
/**
* @return the minSpareThreads
*/
public int getMinSpareThreads() {
return minSpareThreads;
}
/**
* @param minSpareThreads the minSpareThreads to set
*/
public void setMinSpareThreads(int minSpareThreads) {
this.minSpareThreads = minSpareThreads;
}
/**
* @return the maxSpareThreads
*/
public int getMaxSpareThreads() {
return maxSpareThreads;
}
/**
* @param maxSpareThreads the maxSpareThreads to set
*/
public void setMaxSpareThreads(int maxSpareThreads) {
this.maxSpareThreads = maxSpareThreads;
}
/**
* @return the currentThreadCount
*/
public int getCurrentThreadCount() {
return currentThreadCount;
}
/**
* @param currentThreadCount the currentThreadCount to set
*/
public void setCurrentThreadCount(int currentThreadCount) {
this.currentThreadCount = currentThreadCount;
}
/**
* @return the currentThreadsBusy
*/
public int getCurrentThreadsBusy() {
return currentThreadsBusy;
}
/**
* @param currentThreadsBusy the currentThreadsBusy to set
*/
public void setCurrentThreadsBusy(int currentThreadsBusy) {
this.currentThreadsBusy = currentThreadsBusy;
}
/**
* @return the stopThePool
*/
public boolean isStopThePool() {
return stopThePool;
}
/**
* @param stopThePool the stopThePool to set
*/
public void setStopThePool(boolean stopThePool) {
this.stopThePool = stopThePool;
}
}
/**
* 一个线程池包括以下四个基本组成部分:
1、线程池管理器(ThreadPool):用于创建并管理线程池,包括 创建线程池,销毁线程池,添加新任务;
2、工作线程(PoolWorker):线程池中线程,在没有任务时处于等待状态,可以循环的执行任务;
3、任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行,
它主要规定了任务的入口,任务执行完后的收尾工作,任务的执行状态等;
4、任务队列(taskQueue):用于存放没有处理的任务。提供一种缓冲机制。
*/
package threadpoolmanager;
import java.util.Vector;
import threadpoolmanager.MonitorRunnable;
/**
* 线程池管理器
* @author Administrator
*
*/
public class ThreadPoolManager {
public static final int MAX_THREADS=200; //最大线程数
public static final int MAX_SPARE_THREADS=50; //最大空闲线程数
public static final int MIN_SPARE_THREADS=10; //最小空闲线程数
private Vector<WorkThread> pool; //工作线程队列
private MonitorRunnable monitor; // 监控线程内部类全局变量
private int maxThreads;
private int minSpareThreads;
private int maxSpareThreads;
private int currentThreadCount; //当前线程数量
private int currentThreadsBusy; //当前繁忙线程的数量
private boolean stopThePool; //关闭线程池的标志
/*
* 初始化线程池
*/
public ThreadPoolManager() {
maxThreads = MAX_THREADS;
maxSpareThreads = MAX_SPARE_THREADS;
minSpareThreads = MIN_SPARE_THREADS;
//默认当前线程、当前繁忙线程、线程池关闭标识分别为0、0、false
currentThreadCount = 0;
currentThreadsBusy = 0;
stopThePool = false;
}
public synchronized void start(){
//计算最大空闲线程和最小空闲线程
adjustLimits();
openThreads(minSpareThreads);
//启动监控线程,程序开始运行
monitor=new MonitorRunnable(this);
}
/*
* 这个方法给外部调用,把具体的任务传进来。
* 从这个方法可以看到,它实际上是把任务接过来,判断当前线程有多少,有空闲的就到池里面去取,
* 实际上是调用池里面的WorkThread线程来干活
*/
public synchronized void runIt(Task task){
if(task==null){
throw new NullPointerException("任务为空");
}
if(currentThreadCount==0||stopThePool){
throw new IllegalStateException("没有线程在运行");
}
WorkThread thread=null;
synchronized (this) {
if(currentThreadCount==currentThreadsBusy){
if(currentThreadCount<maxThreads){
int toOpen=currentThreadCount+minSpareThreads;
openThreads(toOpen);
}else{
while(currentThreadCount==currentThreadsBusy){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(currentThreadCount==0||stopThePool){
throw new IllegalStateException("没有线程在运行");
}
}
}
}
// 找到pool里最末端的一个线程。然后从pool里除去,currentThreadsBusy加1,表示忙的线程多一个了。
thread=pool.lastElement();
pool.removeElement(thread);
currentThreadsBusy++;
}
// 上面从pool里取出来线程了ControlRunnable,调用它的runIt方法,开始运行
thread.runIt(task);
}
/*
* 检测线程数量
* 如果当前线程个数 - 正在繁忙的线程 比 最大空闲线程数大,释放多余的空闲线程
*/
public synchronized void checkSpareThreads(){
if(stopThePool){
return;
}
if(currentThreadCount-currentThreadsBusy>maxSpareThreads){
int toFree=currentThreadCount-currentThreadsBusy-maxSpareThreads;
for(int i=0;i<toFree;i++){
WorkThread thread=pool.firstElement();
pool.removeElement(thread);
thread.shutdown();
currentThreadCount--;
}
}
}
/*
* 关闭线程池
*/
public synchronized void shutdown(){
if(!stopThePool){
stopThePool=true;
monitor.shutdown();
monitor=null;
for(int i=0;i<(currentThreadCount-currentThreadsBusy);i++){
WorkThread thread=pool.elementAt(i);
thread.shutdown();
}
currentThreadCount=currentThreadsBusy=0;
pool=null;
notifyAll();
}
}
/*
* 回收工作线程
*/
public synchronized void returnWorkThread(WorkThread work){
if(currentThreadCount==0||stopThePool){
work.shutdown();
return;
}
currentThreadsBusy--;
pool.addElement(work);
}
/*
* 计算最大空闲线程和最小空闲线程
*/
private void adjustLimits(){
if (maxThreads <= 0) {
maxThreads = MAX_THREADS;
}
if (maxSpareThreads >= maxThreads) {
maxSpareThreads = maxThreads;
}
if (maxSpareThreads <= 0) {
if (1 == maxThreads) {
maxSpareThreads = 1;
} else {
maxSpareThreads = maxThreads / 2;
}
}
if (minSpareThreads > maxSpareThreads) {
minSpareThreads = maxSpareThreads;
}
if (minSpareThreads <= 0) {
if (1 == maxSpareThreads) {
minSpareThreads = 1;
} else {
minSpareThreads = maxSpareThreads / 2;
}
}
}
/*
* 创建线程池
*/
private void openThreads(int toOpen){
if(toOpen>maxThreads){
toOpen=maxThreads;
}
if(0==currentThreadCount){
// 初始开minSpareThreads 10个元素
pool=new Vector<WorkThread>(toOpen);
}
for(int i=currentThreadCount;i<toOpen;i++){
WorkThread thread=new WorkThread(this);
pool.addElement(thread);
}
currentThreadCount=toOpen; //当前线程个数
}
/**
* @return the pool
*/
public Vector<WorkThread> getPool() {
return pool;
}
/**
* @param pool the pool to set
*/
public void setPool(Vector<WorkThread> pool) {
this.pool = pool;
}
/**
* @return the maxThreads
*/
public int getMaxThreads() {
return maxThreads;
}
/**
* @param maxThreads the maxThreads to set
*/
public void setMaxThreads(int maxThreads) {
this.maxThreads = maxThreads;
}
/**
* @return the minSpareThreads
*/
public int getMinSpareThreads() {
return minSpareThreads;
}
/**
* @param minSpareThreads the minSpareThreads to set
*/
public void setMinSpareThreads(int minSpareThreads) {
this.minSpareThreads = minSpareThreads;
}
/**
* @return the maxSpareThreads
*/
public int getMaxSpareThreads() {
return maxSpareThreads;
}
/**
* @param maxSpareThreads the maxSpareThreads to set
*/
public void setMaxSpareThreads(int maxSpareThreads) {
this.maxSpareThreads = maxSpareThreads;
}
/**
* @return the currentThreadCount
*/
public int getCurrentThreadCount() {
return currentThreadCount;
}
/**
* @param currentThreadCount the currentThreadCount to set
*/
public void setCurrentThreadCount(int currentThreadCount) {
this.currentThreadCount = currentThreadCount;
}
/**
* @return the currentThreadsBusy
*/
public int getCurrentThreadsBusy() {
return currentThreadsBusy;
}
/**
* @param currentThreadsBusy the currentThreadsBusy to set
*/
public void setCurrentThreadsBusy(int currentThreadsBusy) {
this.currentThreadsBusy = currentThreadsBusy;
}
/**
* @return the stopThePool
*/
public boolean isStopThePool() {
return stopThePool;
}
/**
* @param stopThePool the stopThePool to set
*/
public void setStopThePool(boolean stopThePool) {
this.stopThePool = stopThePool;
}
}
Java代码
package threadpoolmanager;
/**
* 工作线程
* @author Administrator
*
*/
public class WorkThread implements Runnable {
//线程池管理器对象
private ThreadPoolManager poolManager;
private boolean shutdown;
private boolean running;
private Task task;
private Thread thread;
public WorkThread(ThreadPoolManager poolManager) {
this.poolManager=poolManager;
shutdown=false;
running=false;
task=null;
thread=new Thread(this);
thread.start();
}
@Override
public void run() {
while(true){
synchronized (this) {
if(!running&&!shutdown){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if(shutdown){
break;
}
try{
task.execute();
}catch(Exception e){
e.printStackTrace();
}finally{
task=null;
running=false;
poolManager.returnWorkThread(this);
}
}
}
/*
* 接收任务,并唤醒该线程
* 让线程开始运行
*/
public synchronized void runIt(Task task){
if(task==null){
throw new NullPointerException("该任务为Null");
}
this.task=task;
running=true;
this.notify();
}
public synchronized void shutdown(){
shutdown=true;
this.notify();
}
}
package threadpoolmanager;
/**
* 工作线程
* @author Administrator
*
*/
public class WorkThread implements Runnable {
//线程池管理器对象
private ThreadPoolManager poolManager;
private boolean shutdown;
private boolean running;
private Task task;
private Thread thread;
public WorkThread(ThreadPoolManager poolManager) {
this.poolManager=poolManager;
shutdown=false;
running=false;
task=null;
thread=new Thread(this);
thread.start();
}
@Override
public void run() {
while(true){
synchronized (this) {
if(!running&&!shutdown){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if(shutdown){
break;
}
try{
task.execute();
}catch(Exception e){
e.printStackTrace();
}finally{
task=null;
running=false;
poolManager.returnWorkThread(this);
}
}
}
/*
* 接收任务,并唤醒该线程
* 让线程开始运行
*/
public synchronized void runIt(Task task){
if(task==null){
throw new NullPointerException("该任务为Null");
}
this.task=task;
running=true;
this.notify();
}
public synchronized void shutdown(){
shutdown=true;
this.notify();
}
}
Java代码
package threadpoolmanager;
/**
* 监控线程
* @author Administrator
*
*/
public class MonitorRunnable implements Runnable {
private ThreadPoolManager manager;
private boolean shutdown;
private Thread thread;
private static final int WORK_WAIT_TIMEOUT = 60 * 1000; // 超时时间
public MonitorRunnable(ThreadPoolManager manager) {
super();
this.manager = manager;
shutdown=false;
thread=new Thread(this);
thread.start();
}
@Override
public void run() {
while(true){
synchronized (this) {
try {
this.wait(WORK_WAIT_TIMEOUT);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//是否要中止运行
if(shutdown){
break;
}
//一直检测当前线程数,如果当前线程个数 - 正在繁忙的线程 比 最大空闲线程数大,释放多的线程
manager.checkSpareThreads();
}
}
public synchronized void shutdown(){
shutdown=true;
this.notify();
}
}
package threadpoolmanager;
/**
* 监控线程
* @author Administrator
*
*/
public class MonitorRunnable implements Runnable {
private ThreadPoolManager manager;
private boolean shutdown;
private Thread thread;
private static final int WORK_WAIT_TIMEOUT = 60 * 1000; // 超时时间
public MonitorRunnable(ThreadPoolManager manager) {
super();
this.manager = manager;
shutdown=false;
thread=new Thread(this);
thread.start();
}
@Override
public void run() {
while(true){
synchronized (this) {
try {
this.wait(WORK_WAIT_TIMEOUT);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//是否要中止运行
if(shutdown){
break;
}
//一直检测当前线程数,如果当前线程个数 - 正在繁忙的线程 比 最大空闲线程数大,释放多的线程
manager.checkSpareThreads();
}
}
public synchronized void shutdown(){
shutdown=true;
this.notify();
}
}
Java代码
package threadpoolmanager;
public interface Task {
public void execute();
}
* 一个线程池包括以下四个基本组成部分:
1、线程池管理器(ThreadPool):用于创建并管理线程池,包括 创建线程池,销毁线程池,添加新任务;
2、工作线程(PoolWorker):线程池中线程,在没有任务时处于等待状态,可以循环的执行任务;
3、任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行,
它主要规定了任务的入口,任务执行完后的收尾工作,任务的执行状态等;
4、任务队列(taskQueue):用于存放没有处理的任务。提供一种缓冲机制。
*/
package threadpoolmanager;
import java.util.Vector;
import threadpoolmanager.MonitorRunnable;
/**
* 线程池管理器
* @author Administrator
*
*/
public class ThreadPoolManager {
public static final int MAX_THREADS=200; //最大线程数
public static final int MAX_SPARE_THREADS=50; //最大空闲线程数
public static final int MIN_SPARE_THREADS=10; //最小空闲线程数
private Vector<WorkThread> pool; //工作线程队列
private MonitorRunnable monitor; // 监控线程内部类全局变量
private int maxThreads;
private int minSpareThreads;
private int maxSpareThreads;
private int currentThreadCount; //当前线程数量
private int currentThreadsBusy; //当前繁忙线程的数量
private boolean stopThePool; //关闭线程池的标志
/*
* 初始化线程池
*/
public ThreadPoolManager() {
maxThreads = MAX_THREADS;
maxSpareThreads = MAX_SPARE_THREADS;
minSpareThreads = MIN_SPARE_THREADS;
//默认当前线程、当前繁忙线程、线程池关闭标识分别为0、0、false
currentThreadCount = 0;
currentThreadsBusy = 0;
stopThePool = false;
}
public synchronized void start(){
//计算最大空闲线程和最小空闲线程
adjustLimits();
openThreads(minSpareThreads);
//启动监控线程,程序开始运行
monitor=new MonitorRunnable(this);
}
/*
* 这个方法给外部调用,把具体的任务传进来。
* 从这个方法可以看到,它实际上是把任务接过来,判断当前线程有多少,有空闲的就到池里面去取,
* 实际上是调用池里面的WorkThread线程来干活
*/
public synchronized void runIt(Task task){
if(task==null){
throw new NullPointerException("任务为空");
}
if(currentThreadCount==0||stopThePool){
throw new IllegalStateException("没有线程在运行");
}
WorkThread thread=null;
synchronized (this) {
if(currentThreadCount==currentThreadsBusy){
if(currentThreadCount<maxThreads){
int toOpen=currentThreadCount+minSpareThreads;
openThreads(toOpen);
}else{
while(currentThreadCount==currentThreadsBusy){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(currentThreadCount==0||stopThePool){
throw new IllegalStateException("没有线程在运行");
}
}
}
}
// 找到pool里最末端的一个线程。然后从pool里除去,currentThreadsBusy加1,表示忙的线程多一个了。
thread=pool.lastElement();
pool.removeElement(thread);
currentThreadsBusy++;
}
// 上面从pool里取出来线程了ControlRunnable,调用它的runIt方法,开始运行
thread.runIt(task);
}
/*
* 检测线程数量
* 如果当前线程个数 - 正在繁忙的线程 比 最大空闲线程数大,释放多余的空闲线程
*/
public synchronized void checkSpareThreads(){
if(stopThePool){
return;
}
if(currentThreadCount-currentThreadsBusy>maxSpareThreads){
int toFree=currentThreadCount-currentThreadsBusy-maxSpareThreads;
for(int i=0;i<toFree;i++){
WorkThread thread=pool.firstElement();
pool.removeElement(thread);
thread.shutdown();
currentThreadCount--;
}
}
}
/*
* 关闭线程池
*/
public synchronized void shutdown(){
if(!stopThePool){
stopThePool=true;
monitor.shutdown();
monitor=null;
for(int i=0;i<(currentThreadCount-currentThreadsBusy);i++){
WorkThread thread=pool.elementAt(i);
thread.shutdown();
}
currentThreadCount=currentThreadsBusy=0;
pool=null;
notifyAll();
}
}
/*
* 回收工作线程
*/
public synchronized void returnWorkThread(WorkThread work){
if(currentThreadCount==0||stopThePool){
work.shutdown();
return;
}
currentThreadsBusy--;
pool.addElement(work);
}
/*
* 计算最大空闲线程和最小空闲线程
*/
private void adjustLimits(){
if (maxThreads <= 0) {
maxThreads = MAX_THREADS;
}
if (maxSpareThreads >= maxThreads) {
maxSpareThreads = maxThreads;
}
if (maxSpareThreads <= 0) {
if (1 == maxThreads) {
maxSpareThreads = 1;
} else {
maxSpareThreads = maxThreads / 2;
}
}
if (minSpareThreads > maxSpareThreads) {
minSpareThreads = maxSpareThreads;
}
if (minSpareThreads <= 0) {
if (1 == maxSpareThreads) {
minSpareThreads = 1;
} else {
minSpareThreads = maxSpareThreads / 2;
}
}
}
/*
* 创建线程池
*/
private void openThreads(int toOpen){
if(toOpen>maxThreads){
toOpen=maxThreads;
}
if(0==currentThreadCount){
// 初始开minSpareThreads 10个元素
pool=new Vector<WorkThread>(toOpen);
}
for(int i=currentThreadCount;i<toOpen;i++){
WorkThread thread=new WorkThread(this);
pool.addElement(thread);
}
currentThreadCount=toOpen; //当前线程个数
}
/**
* @return the pool
*/
public Vector<WorkThread> getPool() {
return pool;
}
/**
* @param pool the pool to set
*/
public void setPool(Vector<WorkThread> pool) {
this.pool = pool;
}
/**
* @return the maxThreads
*/
public int getMaxThreads() {
return maxThreads;
}
/**
* @param maxThreads the maxThreads to set
*/
public void setMaxThreads(int maxThreads) {
this.maxThreads = maxThreads;
}
/**
* @return the minSpareThreads
*/
public int getMinSpareThreads() {
return minSpareThreads;
}
/**
* @param minSpareThreads the minSpareThreads to set
*/
public void setMinSpareThreads(int minSpareThreads) {
this.minSpareThreads = minSpareThreads;
}
/**
* @return the maxSpareThreads
*/
public int getMaxSpareThreads() {
return maxSpareThreads;
}
/**
* @param maxSpareThreads the maxSpareThreads to set
*/
public void setMaxSpareThreads(int maxSpareThreads) {
this.maxSpareThreads = maxSpareThreads;
}
/**
* @return the currentThreadCount
*/
public int getCurrentThreadCount() {
return currentThreadCount;
}
/**
* @param currentThreadCount the currentThreadCount to set
*/
public void setCurrentThreadCount(int currentThreadCount) {
this.currentThreadCount = currentThreadCount;
}
/**
* @return the currentThreadsBusy
*/
public int getCurrentThreadsBusy() {
return currentThreadsBusy;
}
/**
* @param currentThreadsBusy the currentThreadsBusy to set
*/
public void setCurrentThreadsBusy(int currentThreadsBusy) {
this.currentThreadsBusy = currentThreadsBusy;
}
/**
* @return the stopThePool
*/
public boolean isStopThePool() {
return stopThePool;
}
/**
* @param stopThePool the stopThePool to set
*/
public void setStopThePool(boolean stopThePool) {
this.stopThePool = stopThePool;
}
}
/**
* 一个线程池包括以下四个基本组成部分:
1、线程池管理器(ThreadPool):用于创建并管理线程池,包括 创建线程池,销毁线程池,添加新任务;
2、工作线程(PoolWorker):线程池中线程,在没有任务时处于等待状态,可以循环的执行任务;
3、任务接口(Task):每个任务必须实现的接口,以供工作线程调度任务的执行,
它主要规定了任务的入口,任务执行完后的收尾工作,任务的执行状态等;
4、任务队列(taskQueue):用于存放没有处理的任务。提供一种缓冲机制。
*/
package threadpoolmanager;
import java.util.Vector;
import threadpoolmanager.MonitorRunnable;
/**
* 线程池管理器
* @author Administrator
*
*/
public class ThreadPoolManager {
public static final int MAX_THREADS=200; //最大线程数
public static final int MAX_SPARE_THREADS=50; //最大空闲线程数
public static final int MIN_SPARE_THREADS=10; //最小空闲线程数
private Vector<WorkThread> pool; //工作线程队列
private MonitorRunnable monitor; // 监控线程内部类全局变量
private int maxThreads;
private int minSpareThreads;
private int maxSpareThreads;
private int currentThreadCount; //当前线程数量
private int currentThreadsBusy; //当前繁忙线程的数量
private boolean stopThePool; //关闭线程池的标志
/*
* 初始化线程池
*/
public ThreadPoolManager() {
maxThreads = MAX_THREADS;
maxSpareThreads = MAX_SPARE_THREADS;
minSpareThreads = MIN_SPARE_THREADS;
//默认当前线程、当前繁忙线程、线程池关闭标识分别为0、0、false
currentThreadCount = 0;
currentThreadsBusy = 0;
stopThePool = false;
}
public synchronized void start(){
//计算最大空闲线程和最小空闲线程
adjustLimits();
openThreads(minSpareThreads);
//启动监控线程,程序开始运行
monitor=new MonitorRunnable(this);
}
/*
* 这个方法给外部调用,把具体的任务传进来。
* 从这个方法可以看到,它实际上是把任务接过来,判断当前线程有多少,有空闲的就到池里面去取,
* 实际上是调用池里面的WorkThread线程来干活
*/
public synchronized void runIt(Task task){
if(task==null){
throw new NullPointerException("任务为空");
}
if(currentThreadCount==0||stopThePool){
throw new IllegalStateException("没有线程在运行");
}
WorkThread thread=null;
synchronized (this) {
if(currentThreadCount==currentThreadsBusy){
if(currentThreadCount<maxThreads){
int toOpen=currentThreadCount+minSpareThreads;
openThreads(toOpen);
}else{
while(currentThreadCount==currentThreadsBusy){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(currentThreadCount==0||stopThePool){
throw new IllegalStateException("没有线程在运行");
}
}
}
}
// 找到pool里最末端的一个线程。然后从pool里除去,currentThreadsBusy加1,表示忙的线程多一个了。
thread=pool.lastElement();
pool.removeElement(thread);
currentThreadsBusy++;
}
// 上面从pool里取出来线程了ControlRunnable,调用它的runIt方法,开始运行
thread.runIt(task);
}
/*
* 检测线程数量
* 如果当前线程个数 - 正在繁忙的线程 比 最大空闲线程数大,释放多余的空闲线程
*/
public synchronized void checkSpareThreads(){
if(stopThePool){
return;
}
if(currentThreadCount-currentThreadsBusy>maxSpareThreads){
int toFree=currentThreadCount-currentThreadsBusy-maxSpareThreads;
for(int i=0;i<toFree;i++){
WorkThread thread=pool.firstElement();
pool.removeElement(thread);
thread.shutdown();
currentThreadCount--;
}
}
}
/*
* 关闭线程池
*/
public synchronized void shutdown(){
if(!stopThePool){
stopThePool=true;
monitor.shutdown();
monitor=null;
for(int i=0;i<(currentThreadCount-currentThreadsBusy);i++){
WorkThread thread=pool.elementAt(i);
thread.shutdown();
}
currentThreadCount=currentThreadsBusy=0;
pool=null;
notifyAll();
}
}
/*
* 回收工作线程
*/
public synchronized void returnWorkThread(WorkThread work){
if(currentThreadCount==0||stopThePool){
work.shutdown();
return;
}
currentThreadsBusy--;
pool.addElement(work);
}
/*
* 计算最大空闲线程和最小空闲线程
*/
private void adjustLimits(){
if (maxThreads <= 0) {
maxThreads = MAX_THREADS;
}
if (maxSpareThreads >= maxThreads) {
maxSpareThreads = maxThreads;
}
if (maxSpareThreads <= 0) {
if (1 == maxThreads) {
maxSpareThreads = 1;
} else {
maxSpareThreads = maxThreads / 2;
}
}
if (minSpareThreads > maxSpareThreads) {
minSpareThreads = maxSpareThreads;
}
if (minSpareThreads <= 0) {
if (1 == maxSpareThreads) {
minSpareThreads = 1;
} else {
minSpareThreads = maxSpareThreads / 2;
}
}
}
/*
* 创建线程池
*/
private void openThreads(int toOpen){
if(toOpen>maxThreads){
toOpen=maxThreads;
}
if(0==currentThreadCount){
// 初始开minSpareThreads 10个元素
pool=new Vector<WorkThread>(toOpen);
}
for(int i=currentThreadCount;i<toOpen;i++){
WorkThread thread=new WorkThread(this);
pool.addElement(thread);
}
currentThreadCount=toOpen; //当前线程个数
}
/**
* @return the pool
*/
public Vector<WorkThread> getPool() {
return pool;
}
/**
* @param pool the pool to set
*/
public void setPool(Vector<WorkThread> pool) {
this.pool = pool;
}
/**
* @return the maxThreads
*/
public int getMaxThreads() {
return maxThreads;
}
/**
* @param maxThreads the maxThreads to set
*/
public void setMaxThreads(int maxThreads) {
this.maxThreads = maxThreads;
}
/**
* @return the minSpareThreads
*/
public int getMinSpareThreads() {
return minSpareThreads;
}
/**
* @param minSpareThreads the minSpareThreads to set
*/
public void setMinSpareThreads(int minSpareThreads) {
this.minSpareThreads = minSpareThreads;
}
/**
* @return the maxSpareThreads
*/
public int getMaxSpareThreads() {
return maxSpareThreads;
}
/**
* @param maxSpareThreads the maxSpareThreads to set
*/
public void setMaxSpareThreads(int maxSpareThreads) {
this.maxSpareThreads = maxSpareThreads;
}
/**
* @return the currentThreadCount
*/
public int getCurrentThreadCount() {
return currentThreadCount;
}
/**
* @param currentThreadCount the currentThreadCount to set
*/
public void setCurrentThreadCount(int currentThreadCount) {
this.currentThreadCount = currentThreadCount;
}
/**
* @return the currentThreadsBusy
*/
public int getCurrentThreadsBusy() {
return currentThreadsBusy;
}
/**
* @param currentThreadsBusy the currentThreadsBusy to set
*/
public void setCurrentThreadsBusy(int currentThreadsBusy) {
this.currentThreadsBusy = currentThreadsBusy;
}
/**
* @return the stopThePool
*/
public boolean isStopThePool() {
return stopThePool;
}
/**
* @param stopThePool the stopThePool to set
*/
public void setStopThePool(boolean stopThePool) {
this.stopThePool = stopThePool;
}
}
Java代码
package threadpoolmanager;
/**
* 工作线程
* @author Administrator
*
*/
public class WorkThread implements Runnable {
//线程池管理器对象
private ThreadPoolManager poolManager;
private boolean shutdown;
private boolean running;
private Task task;
private Thread thread;
public WorkThread(ThreadPoolManager poolManager) {
this.poolManager=poolManager;
shutdown=false;
running=false;
task=null;
thread=new Thread(this);
thread.start();
}
@Override
public void run() {
while(true){
synchronized (this) {
if(!running&&!shutdown){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if(shutdown){
break;
}
try{
task.execute();
}catch(Exception e){
e.printStackTrace();
}finally{
task=null;
running=false;
poolManager.returnWorkThread(this);
}
}
}
/*
* 接收任务,并唤醒该线程
* 让线程开始运行
*/
public synchronized void runIt(Task task){
if(task==null){
throw new NullPointerException("该任务为Null");
}
this.task=task;
running=true;
this.notify();
}
public synchronized void shutdown(){
shutdown=true;
this.notify();
}
}
package threadpoolmanager;
/**
* 工作线程
* @author Administrator
*
*/
public class WorkThread implements Runnable {
//线程池管理器对象
private ThreadPoolManager poolManager;
private boolean shutdown;
private boolean running;
private Task task;
private Thread thread;
public WorkThread(ThreadPoolManager poolManager) {
this.poolManager=poolManager;
shutdown=false;
running=false;
task=null;
thread=new Thread(this);
thread.start();
}
@Override
public void run() {
while(true){
synchronized (this) {
if(!running&&!shutdown){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if(shutdown){
break;
}
try{
task.execute();
}catch(Exception e){
e.printStackTrace();
}finally{
task=null;
running=false;
poolManager.returnWorkThread(this);
}
}
}
/*
* 接收任务,并唤醒该线程
* 让线程开始运行
*/
public synchronized void runIt(Task task){
if(task==null){
throw new NullPointerException("该任务为Null");
}
this.task=task;
running=true;
this.notify();
}
public synchronized void shutdown(){
shutdown=true;
this.notify();
}
}
Java代码
package threadpoolmanager;
/**
* 监控线程
* @author Administrator
*
*/
public class MonitorRunnable implements Runnable {
private ThreadPoolManager manager;
private boolean shutdown;
private Thread thread;
private static final int WORK_WAIT_TIMEOUT = 60 * 1000; // 超时时间
public MonitorRunnable(ThreadPoolManager manager) {
super();
this.manager = manager;
shutdown=false;
thread=new Thread(this);
thread.start();
}
@Override
public void run() {
while(true){
synchronized (this) {
try {
this.wait(WORK_WAIT_TIMEOUT);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//是否要中止运行
if(shutdown){
break;
}
//一直检测当前线程数,如果当前线程个数 - 正在繁忙的线程 比 最大空闲线程数大,释放多的线程
manager.checkSpareThreads();
}
}
public synchronized void shutdown(){
shutdown=true;
this.notify();
}
}
package threadpoolmanager;
/**
* 监控线程
* @author Administrator
*
*/
public class MonitorRunnable implements Runnable {
private ThreadPoolManager manager;
private boolean shutdown;
private Thread thread;
private static final int WORK_WAIT_TIMEOUT = 60 * 1000; // 超时时间
public MonitorRunnable(ThreadPoolManager manager) {
super();
this.manager = manager;
shutdown=false;
thread=new Thread(this);
thread.start();
}
@Override
public void run() {
while(true){
synchronized (this) {
try {
this.wait(WORK_WAIT_TIMEOUT);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//是否要中止运行
if(shutdown){
break;
}
//一直检测当前线程数,如果当前线程个数 - 正在繁忙的线程 比 最大空闲线程数大,释放多的线程
manager.checkSpareThreads();
}
}
public synchronized void shutdown(){
shutdown=true;
this.notify();
}
}
Java代码
package threadpoolmanager;
public interface Task {
public void execute();
}
发表评论
-
40个UI设计工具盒资源
2011-01-28 11:18 1117转自: http://zxq198181.iteye.com ... -
autocomplete
2011-01-21 09:27 1157在使用jquery的autocomplete插件, 修改了au ... -
java.lang.reflect.InvocationTargetException
2011-01-05 10:29 1323总结两问题: 1.今天访问数据库, 调用存储方法, 抛出jav ... -
mysql数据表常用操作
2010-12-30 14:54 658//主键 alter table tabelname a ... -
数据库设计
2010-12-29 14:33 800数 据 库 设 计 经 验 谈 ... -
数据库设计准则信息
2010-12-29 14:05 505http://www.ibm.com/developerwor ... -
System.getProperty()参数大全, 留着以后用
2010-12-29 13:48 517# System.getProperty()参数大全 # ...
相关推荐
在Java编程中,线程池是一种高效管理线程资源的方式,可以提高系统的性能和响应速度。本篇将探讨如何模拟Java的JDK线程池执行流程,以理解其设计原理。核心知识点包括线程池的执行策略、接口设计以及异常处理。 ...
1、为什么需要使用线程池 1.1 创建/销毁线程伴随着系统开销,过于频繁的创建/销毁线程,会很大程度上影响处理效率。 记创建线程消耗时间T1,执行任务消耗时间T2,销毁线程消耗时间T3,如果T1+T3>T2,那说明开启一个...
线程池是一种多线程处理形式,通过预先创建一定数量的线程并管理它们,以提高系统的效率和响应性。在计算机科学中,特别是在软件开发领域,线程池是操作系统或者编程语言中的一种资源管理技术。它允许程序预先启动一...
1. **线程数量控制**:线程池应有一个合理的最大线程数,过多的线程会消耗大量内存,而过少可能无法充分利用多核处理器。 2. **任务调度策略**:线程池可以采用不同的策略来决定哪个线程执行哪个任务,如优先级调度...
1. Spring提供了一个名为ThreadPoolTaskExecutor的实现,它基于Java的ExecutorService接口,允许我们自定义线程池配置,如核心线程数、最大线程数、队列容量、超时时间等。 2. 通过在配置文件中声明一个...
1. 为什么要用线程池? 线程池的主要优点在于资源管理和任务调度。当系统中有大量短生命周期的任务时,使用线程池可以避免反复创建和销毁线程的开销。此外,线程池能提供更好的控制,如限制并发执行的任务数量,...
线程池是一种优化资源管理的机制,通过预先创建并维护一组可重用的线程,避免频繁地创建和销毁线程带来的性能开销。在Java、C++等编程语言中,线程池广泛应用于并发处理,提高系统效率,降低系统的资源消耗。本项目...
2. **任务分配**:当一个 Trigger 触发时,调度器会从线程池中选择一个空闲线程,分配给 Job 执行。如果所有线程都在忙碌,新的 Trigger 将被暂时挂起,等待线程池中有线程可用。 3. **任务执行**:线程执行 ...
一、要实现高效的线程池,可以考虑以下几点 二、实现线程池可以按照以下步骤进行 三、简单的C++线程池代码示例 四、 基于boost编写的源码库 - 线程池 4.1 基于boost编写的源码库地址 4.2 boost线程池的先进先出、...
java线程池是一种高效的并发编程技术,可以帮助开发者更好地管理线程资源,提高系统的性能和可靠性。然而,在使用java线程池时,一个常见的问题是:使用完线程池后到底要不要关闭?本文将通过实例代码和详细解释,...
线程池是一种多线程处理形式,预先创建一定数量的线程,放入池中,当有任务需要执行时,直接从池中获取线程来执行任务,而不是每次都创建新的线程,从而提高了系统资源的利用率,降低了系统开销。 线程池的核心组件...
在IT领域,线程池是一种优化并发处理的机制,它在多核或多处理器系统中尤其重要,能够有效地管理和调度线程资源,减少线程创建和销毁的开销。本资源包含了一个关于C++线程池的PPT,下面将详细探讨C++线程池的相关...
1. 初始化线程池:调用`InitializeThreadpoolEnvironment`函数创建线程池环境。 2. 创建线程池工作项:使用`CreateThreadpoolWork`函数定义一个工作项,该工作项包含要执行的函数和其参数。 3. 提交工作项:调用`...
1. **FixedThreadPool**:创建一个固定大小的线程池,线程数量由用户指定。当所有线程都在执行任务时,新提交的任务会被放入队列中等待执行。 2. **CachedThreadPool**:创建一个可根据需要创建新线程的线程池,但在...
Java 线程池是 Java 语言中的一个重要概念,它允许开发者创建和管理多个线程,以提高程序的并发性和性能。下面是对给定文件的解析,包括 title、description、标签和部分内容的解析。 标题解析 标题 "Java 线程池...
下面的例子中,我们有一个并行流,这个并行流使用了一个自定义的线程池去计算1到 1,000,000的和。 知识点:可以使用ForkJoinPool的构造方法并设定并行级别来创建一个自定义的线程池。 4. 总结 我们简要地看了一下...
1. **线程池工作原理** 线程池由一组可重用的线程组成,当有新的任务需要执行时,线程池会从已创建的线程中选择一个空闲线程来执行任务,而不是每次都创建新的线程。任务完成后,线程不会立即销毁,而是返回线程池...
线程池是一种管理线程的机制,它预先创建一定数量的线程,当有任务需要执行时,线程池会分配一个空闲的线程去执行任务,而不是每次都创建新的线程。这种设计可以避免频繁创建和销毁线程带来的开销,提高系统的响应...
1. **线程池大小**:线程池中线程的最大数量,可以通过参数进行配置。 2. **工作队列**:用于存放待处理任务的队列,当所有线程都在忙碌时,新任务会被放入队列等待。 3. **线程管理策略**:当工作队列满时,线程池...
1. **初始化**:线程池在启动时会创建一定数量的线程,这些线程称为工作线程。这些线程处于等待状态,等待接收任务执行。 2. **任务提交**:当有新的任务需要执行时,不是立即创建新线程,而是将任务添加到任务队列...