Java版线程池实现
线程池调度技术原理:
package test.threadpool;
import java.util.*;
import test.cfg.*;
public class ThreadPool {
private int reserve = 0; //保留线程
private int minPools = 10; //最小连接池数目,预启动线程数目
private int maxActive = 70; //最多活动线程数目
private int maxPools = 100; //最大连接池数目
private int checkThreadPeriod = 5; //检查连接池的周期
ArrayList m_ThreadList; //工作线程列表
ArrayList m_ReserveList; //保留线程链表
LinkedList m_RunList = null; //工作任务列表
int freeThreadCount = 0;//未被使用的线程数目
private java.util.Timer timer = null;//定时器
static Object o = new Object();
public void setMinPools(int minPools) {
this.minPools = minPools;
}
public void setMaxPools(int maxPools) {
this.maxPools = maxPools;
}
public void setCheckThreadPeriod(int checkThreadPeriod) {
this.checkThreadPeriod = checkThreadPeriod;
}
/**
* 初始化线程池,由于各个线程启动的时候是有一定的时间间隔,启动的时候会有一定的时间
*
*/
public ThreadPool() {
// reserve = Integer.parseInt(FtpConfig.getValue("reserve"); //从配置文件中获取参数
// minPools = Integer.parseInt(FtpConfig.getValue("minPools"); //从配置文件中获取参数
//maxActive = Integer.parseInt(FtpConfig.getValue("maxActive"); //从配置文件中获取参数
//maxPools = Integer.parseInt(FtpConfig.getValue("maxPools"); //从配置文件中获取参数
//checkThreadPeriod = Integer.parseInt(FtpConfig
// .getValue("monitorPeriod") * 60 * 1000; //以分为轮询单位
m_ThreadList = new ArrayList(); //初始化工作线程链表
m_ReserveList = new ArrayList();
m_RunList = new LinkedList(); //初始化任务列表
ArrayList list = null;
if (reserve > 0)
list = (ArrayList) FtpConfig.getProValueList("reserveList";
for (int i = 0; i < reserve; i++) { //启动保留线程,根据配置链表中的线程列表启动对应的保留线程.保存的是线程的全路径
//class name
try {
Thread thr = (Thread) Class.forName((String) list.get(i))
.newInstance();
m_ReserveList.add(i, thr);
thr.start();
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
}
for (int i = 0; i < minPools; i++) { //初始化空闲线程
WorkerThread temp = new WorkerThread();
m_ThreadList.add(temp); //将线程添加到线程链表中
temp.start(); //启动工作线程
try {
Thread.sleep(10); //每个100us启动一个线程
} catch (Exception e) {
}
}
printDebugInfo();
timer = new Timer(true);//启动定时器
timer.schedule(new CheckThreadTask(this), 0, checkThreadPeriod); //设置定时器调度线程池
}
/**
* 应用程序调用入口,可以是一个封装好的job类,具体视应用而定
* @param work
*/
public synchronized void run(Object work) {
synchronized (m_RunList) { //添加任务到任务链表中
m_RunList.add(work);
m_RunList.notify();
}
}
/**
* monitor 所要采取的动作(轮询)
*
*/
public synchronized void checkAllThreads() {
//printDebugInfo();
//如果空闲线程数少于预启动线程数目,并且没有达到最大的活动线程数时则增加空闲线程
if(freeThreadCount<minPools && m_ThreadList.size()<maxPools){
int count=(minPools-freeThreadCount)>(maxActive-m_ThreadList.size())?(maxActive-m_ThreadList.size())minPools-freeThreadCount);
for(int i=0;i<count;i++){
Thread thr=null;
try{
thr=new WorkerThread();
m_ThreadList.add(thr);
thr.start();
}catch(Exception e){
e.printStackTrace();
}
}
}
if(freeThreadCount>minPools && (m_ThreadList.size()>maxActive) ){
int count=(freeThreadCount-minPools)>(m_ThreadList.size()-maxActive)?(freeThreadCount-minPools)freeThreadCount-minPools);
for(int i=m_ThreadList.size()-1;i>=0&&count>0;i--,count--){
WorkerThread thr=(WorkerThread)m_ThreadList.get(i);
if(thr!=null && thr.isdo){
continue;
}
if(thr!=null){
synchronized(o){
m_ThreadList.remove(i);
try{
thr.stop(); //销毁线程
}catch(Exception e){
e.printStackTrace();
}
freeThreadCount--;
}
}
}
}
for(int i=0;i<m_ThreadList.size();i++){
Thread thr = (Thread)m_ThreadList.get(i);
if(thr !=null && !(thr.isAlive())){
try{
thr.stop(); //销毁原先的线程
//thr = (Thread) Class.forName((String) FtpConfig.getProValueList("reserveList".get(i)).newInstance();
thr=new WorkerThread();
m_ThreadList.remove(i); //去除原先的对象
m_ThreadList.set(i,thr);
thr.start();
}catch(Exception e){
e.printStackTrace();
}
}
}
//调度保留线程
//Iterator lThreadReserveIterator=m_ReserveList.iterator();
for(int i=m_ReserveList.size()-1;i>=0;i--){
Thread thr=(Thread)m_ReserveList.get(i);
if(thr!=null && !(thr.isAlive())){
//m_ReserveList.remove(i);
try{
//thr.destroy(); //销毁原先的线程
thr.stop();
thr = (Thread) Class.forName((String) FtpConfig.getProValueList("reserveList".get(i)).newInstance();
m_ReserveList.remove(i); //去除原先的对象
m_ReserveList.set(i,thr);
thr.start();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
/**
* 打印调试信息
*
*/
public void printDebugInfo() {
System.out.println("m_ThreadList.size()=" + m_ThreadList.size());
System.out.println("freeThreadCount" + freeThreadCount);
}
/**
* 获取任务链表
*
* @return
*/
public LinkedList getRunList() {
return m_RunList;
}
/**
* 增加空闲线程数目
*
*/
public void addFreeThreadCount() {
synchronized (o) {
freeThreadCount++;
}
}
/**
* 减少空闲线程数目
*
*/
public void delFreeThreadCount() {
synchronized (o) {
freeThreadCount--;
}
}
class WorkerThread extends Thread {
boolean running = true;
boolean isdo=false;
String work;
public WorkerThread() {
setDaemon(false); //设置线程为精灵线程
}
/**
* 设置线程的运行状态
*
* @param state
*/
public synchronized void setRunState(boolean state) {
this.running = state;
}
/**
* 获取线程运行状态
* @return
*/
public synchronized boolean getIsdo(){
return isdo;
}
public void run() {
while (running) {
synchronized (o) {
freeThreadCount++;
}
synchronized (m_RunList) {
while (m_RunList.size() == 0) {
try {
m_RunList.wait();
if (!running)
return;
} catch (InterruptedException e) {
}
}
/* do what you want to do */
synchronized (o) { //空闲线程减少
freeThreadCount--;
isdo=true;
/*这里传进来的东西可以是一个socket句柄,用于数据的交换或者是一个其他的对象,具体业务而定*/
// System.out.println(m_RunList.getFirst() + getName());
BaseCtl ctl=(BaseCtl)m_RunList.getFirst();
ctl.doIt();
m_RunList.removeFirst();
isdo=false;
}
}
}
}
}
public static void main(String args[]) {
ThreadPool pool = new ThreadPool();
BaseCtl ctl=new LogonCtl();
pool.run(ctl);
}
package test.threadpool;
import java.util.TimerTask;;
/**
* @author Administrator
* @version 1.0.0
*/
public class CheckThreadTask extends TimerTask{
Object obj=null;
public CheckThreadTask(Object obj){
this.obj=obj;
}
public void run(){
((ThreadPool)obj).checkAllThreads();
}
}
package test.threadpool;
/**
* @author Administrator
* @version 1.0.0
*/
public abstract class BaseCtl { //当然通过这种方式你也可以把socket等句柄传到你的子类中来处理网络应用
public abstract void doIt();
}
package test.threadpool;
/**
* @author Administrator
* @version 1.0.0
*/
public class LogonCtl extends BaseCtl {
public void doIt(){
System.out.println("hello world";
}
}Java版线程池实现线程池调度技术原理:
package test.threadpool;
import java.util.*;
import test.cfg.*;
public class ThreadPool {
private int reserve = 0; //保留线程
private int minPools = 10; //最小连接池数目,预启动线程数目
private int maxActive = 70; //最多活动线程数目
private int maxPools = 100; //最大连接池数目
private int checkThreadPeriod = 5; //检查连接池的周期
ArrayList m_ThreadList; //工作线程列表
ArrayList m_ReserveList; //保留线程链表
LinkedList m_RunList = null; //工作任务列表
int freeThreadCount = 0;//未被使用的线程数目
private java.util.Timer timer = null;//定时器
static Object o = new Object();
public void setMinPools(int minPools) {
this.minPools = minPools;
}
public void setMaxPools(int maxPools) {
this.maxPools = maxPools;
}
public void setCheckThreadPeriod(int checkThreadPeriod) {
this.checkThreadPeriod = checkThreadPeriod;
}
/**
* 初始化线程池,由于各个线程启动的时候是有一定的时间间隔,启动的时候会有一定的时间
*
*/
public ThreadPool() {
// reserve = Integer.parseInt(FtpConfig.getValue("reserve"); //从配置文件中获取参数
// minPools = Integer.parseInt(FtpConfig.getValue("minPools"); //从配置文件中获取参数
//maxActive = Integer.parseInt(FtpConfig.getValue("maxActive"); //从配置文件中获取参数
//maxPools = Integer.parseInt(FtpConfig.getValue("maxPools"); //从配置文件中获取参数
//checkThreadPeriod = Integer.parseInt(FtpConfig
// .getValue("monitorPeriod") * 60 * 1000; //以分为轮询单位
m_ThreadList = new ArrayList(); //初始化工作线程链表
m_ReserveList = new ArrayList();
m_RunList = new LinkedList(); //初始化任务列表
ArrayList list = null;
if (reserve > 0)
list = (ArrayList) FtpConfig.getProValueList("reserveList";
for (int i = 0; i < reserve; i++) { //启动保留线程,根据配置链表中的线程列表启动对应的保留线程.保存的是线程的全路径
//class name
try {
Thread thr = (Thread) Class.forName((String) list.get(i))
.newInstance();
m_ReserveList.add(i, thr);
thr.start();
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
}
for (int i = 0; i < minPools; i++) { //初始化空闲线程
WorkerThread temp = new WorkerThread();
m_ThreadList.add(temp); //将线程添加到线程链表中
temp.start(); //启动工作线程
try {
Thread.sleep(10); //每个100us启动一个线程
} catch (Exception e) {
}
}
printDebugInfo();
timer = new Timer(true);//启动定时器
timer.schedule(new CheckThreadTask(this), 0, checkThreadPeriod); //设置定时器调度线程池
}
/**
* 应用程序调用入口,可以是一个封装好的job类,具体视应用而定
* @param work
*/
public synchronized void run(Object work) {
synchronized (m_RunList) { //添加任务到任务链表中
m_RunList.add(work);
m_RunList.notify();
}
}
/**
* monitor 所要采取的动作(轮询)
*
*/
public synchronized void checkAllThreads() {
//printDebugInfo();
//如果空闲线程数少于预启动线程数目,并且没有达到最大的活动线程数时则增加空闲线程
if(freeThreadCount<minPools && m_ThreadList.size()<maxPools){
int count=(minPools-freeThreadCount)>(maxActive-m_ThreadList.size())?(maxActive-m_ThreadList.size())minPools-freeThreadCount);
for(int i=0;i<count;i++){
Thread thr=null;
try{
thr=new WorkerThread();
m_ThreadList.add(thr);
thr.start();
}catch(Exception e){
e.printStackTrace();
}
}
}
if(freeThreadCount>minPools && (m_ThreadList.size()>maxActive) ){
int count=(freeThreadCount-minPools)>(m_ThreadList.size()-maxActive)?(freeThreadCount-minPools)freeThreadCount-minPools);
for(int i=m_ThreadList.size()-1;i>=0&&count>0;i--,count--){
WorkerThread thr=(WorkerThread)m_ThreadList.get(i);
if(thr!=null && thr.isdo){
continue;
}
if(thr!=null){
synchronized(o){
m_ThreadList.remove(i);
try{
thr.stop(); //销毁线程
}catch(Exception e){
e.printStackTrace();
}
freeThreadCount--;
}
}
}
}
for(int i=0;i<m_ThreadList.size();i++){
Thread thr = (Thread)m_ThreadList.get(i);
if(thr !=null && !(thr.isAlive())){
try{
thr.stop(); //销毁原先的线程
//thr = (Thread) Class.forName((String) FtpConfig.getProValueList("reserveList".get(i)).newInstance();
thr=new WorkerThread();
m_ThreadList.remove(i); //去除原先的对象
m_ThreadList.set(i,thr);
thr.start();
}catch(Exception e){
e.printStackTrace();
}
}
}
//调度保留线程
//Iterator lThreadReserveIterator=m_ReserveList.iterator();
for(int i=m_ReserveList.size()-1;i>=0;i--){
Thread thr=(Thread)m_ReserveList.get(i);
if(thr!=null && !(thr.isAlive())){
//m_ReserveList.remove(i);
try{
//thr.destroy(); //销毁原先的线程
thr.stop();
thr = (Thread) Class.forName((String) FtpConfig.getProValueList("reserveList".get(i)).newInstance();
m_ReserveList.remove(i); //去除原先的对象
m_ReserveList.set(i,thr);
thr.start();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
/**
* 打印调试信息
*
*/
public void printDebugInfo() {
System.out.println("m_ThreadList.size()=" + m_ThreadList.size());
System.out.println("freeThreadCount" + freeThreadCount);
}
/**
* 获取任务链表
*
* @return
*/
public LinkedList getRunList() {
return m_RunList;
}
/**
* 增加空闲线程数目
*
*/
public void addFreeThreadCount() {
synchronized (o) {
freeThreadCount++;
}
}
/**
* 减少空闲线程数目
*
*/
public void delFreeThreadCount() {
synchronized (o) {
freeThreadCount--;
}
}
class WorkerThread extends Thread {
boolean running = true;
boolean isdo=false;
String work;
public WorkerThread() {
setDaemon(false); //设置线程为精灵线程
}
/**
* 设置线程的运行状态
*
* @param state
*/
public synchronized void setRunState(boolean state) {
this.running = state;
}
/**
* 获取线程运行状态
* @return
*/
public synchronized boolean getIsdo(){
return isdo;
}
public void run() {
while (running) {
synchronized (o) {
freeThreadCount++;
}
synchronized (m_RunList) {
while (m_RunList.size() == 0) {
try {
m_RunList.wait();
if (!running)
return;
} catch (InterruptedException e) {
}
}
/* do what you want to do */
synchronized (o) { //空闲线程减少
freeThreadCount--;
isdo=true;
/*这里传进来的东西可以是一个socket句柄,用于数据的交换或者是一个其他的对象,具体业务而定*/
// System.out.println(m_RunList.getFirst() + getName());
BaseCtl ctl=(BaseCtl)m_RunList.getFirst();
ctl.doIt();
m_RunList.removeFirst();
isdo=false;
}
}
}
}
}
public static void main(String args[]) {
ThreadPool pool = new ThreadPool();
BaseCtl ctl=new LogonCtl();
pool.run(ctl);
}
package test.threadpool;
import java.util.TimerTask;;
/**
* @author Administrator
* @version 1.0.0
*/
public class CheckThreadTask extends TimerTask{
Object obj=null;
public CheckThreadTask(Object obj){
this.obj=obj;
}
public void run(){
((ThreadPool)obj).checkAllThreads();
}
}
package test.threadpool;
/**
* @author Administrator
* @version 1.0.0
*/
public abstract class BaseCtl { //当然通过这种方式你也可以把socket等句柄传到你的子类中来处理网络应用
public abstract void doIt();
}
package test.threadpool;
/**
* @author Administrator
* @version 1.0.0
*/
public class LogonCtl extends BaseCtl {
public void doIt(){
System.out.println("hello world";
}
}