------------------------------------------线程池--------------------------------------------------
package threadPoolImpl;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
/**
* 线程池:继承 Timer
*/
@SuppressWarnings("unchecked")
public class ThreadPool extends Timer
{
/** 空闲系数 */
public static final double LIMIT_IDLE = 0.75;
/** 忙碌系数 */
public static final double LIMIT_BUSY = 1.25;
/** 线程池是否健康的标志 */
public static final int POOL_STATE_HEALTHY = 0;
/** 线程池是否空闲的标志 */
public static final int POOL_STATE_IDLE = 1;
/** 线程池是否忙碌的标志 */
public static final int POOL_STATE_BUSY = 2;
/** 线程池实例 */
private static ThreadPool _instance = null;
/** 最大的池数量 */
protected int maxPoolSize = 10;
/** 初始的池数量 */
protected int initPoolSize = 2;
/** 总的任务数量 */
protected int tatolTaskNum = 0;
/** 任务队列集合 */
protected Vector tasksQueue = new Vector();
/** 所有的线程集合 */
protected Vector allThreads = new Vector();
/** 空闲线程集合 */
protected Vector idleThreads = new Vector();
/** 是否初始化的标志 */
protected boolean initialized = false;
/** 是否运行的标志 */
protected boolean isRunnable = true;
/** 线程池状态 */
protected int poolState = 0;
/**
* 根据最大的池数量和初始的池数量来创建线程池
*/
public static ThreadPool getIntance(int maxPoolSize, int initPoolSize)
{
if (_instance == null)
{
_instance = new ThreadPool(maxPoolSize, initPoolSize);
}
return _instance;
}
/** 创建一个空的线程池 */
public static ThreadPool getIntance()
{
if (_instance == null)
{
_instance = new ThreadPool();
}
return _instance;
}
/**
* <默认无参数构造函数。>
*/
protected ThreadPool()
{
// 根据初始的池数量创建线程,并启动(初始是2个线程)
for (int i = 0; i < initPoolSize; i++)
{
PooledThread thread = new PooledThread(this);
thread.start();
}
// 初始化标志修改为true
initialized = true;
// 执行任务,在一秒钟后,每相隔一秒执行一次
this.scheduleAtFixedRate(new TimerTask()
{
@Override
public void run()
{
//
timerEvent();
}
}, 1000, 5000);
}
/**
* <实现有参数的构造>
*/
protected ThreadPool(int maxPoolSize, int initPoolSize)
{
// 判断最大池数量
if (maxPoolSize > 0)
{
this.maxPoolSize = maxPoolSize;
}
// 判断初始化的池数量
if (initPoolSize > 0)
{
this.initPoolSize = initPoolSize;
}
// 判断初始数量是否是大于最大数量
if (this.initPoolSize > this.maxPoolSize)
{
this.initPoolSize = this.maxPoolSize;
}
// 循环初始化线程并启动
for (int i = 0; i < initPoolSize; i++)
{
PooledThread thread = new PooledThread(this);
thread.start();
}
// 修改初始化标志
initialized = true;
// 执行定时任务
this.scheduleAtFixedRate(new TimerTask()
{
@Override
public void run()
{
//
timerEvent();
}
}, 1000, 5000);
}
/**
* <判断线程池的健康状况> <功能详细描述>
*
* @see [类、类#方法、类#成员]
*/
private void timerEvent()
{
// 评定线程池健康状况
if (tatolTaskNum / allThreads.size() < LIMIT_IDLE)
{
poolState = POOL_STATE_IDLE;
}
else if (tatolTaskNum / allThreads.size() > LIMIT_BUSY)
{
poolState = POOL_STATE_BUSY;
}
else
{
poolState = POOL_STATE_HEALTHY;
}
switch (poolState)
{
case POOL_STATE_IDLE:
{
// 杀掉线程池中过余的线程。
while (allThreads.size() > initPoolSize
&& tatolTaskNum / allThreads.size() < LIMIT_IDLE)
{
PooledThread th = getIdleThread(false);
if (th != null)
{
th.kill();
}
else
{
break;
}
}
}
break;
case POOL_STATE_BUSY:
{
// 此处不用生成新线程,在加入新任务时会新增线程。
/*
* if(allThreads.size() < maxPoolSize) { PooledThread thread =
* new PooledThread(this); thread.start(); }
*/
}
break;
case POOL_STATE_HEALTHY:
break;
default:
break;
}
}
/** 设置最大的线程池数量 */
public void setMaxPoolSize(int maxPoolSize)
{
this.maxPoolSize = maxPoolSize;
if (maxPoolSize < getPoolSize())
{
setPoolSize(maxPoolSize);
}
}
/**
* 重设当前线程数 若需杀掉某线程,线程不会立刻杀掉,
* 而会等到线程中的事务处理完成,但此方法会立刻从线程池中移除该线程,不会等待事务处理结束
*
* @param size 设置池子的大小
*/
public void setPoolSize(int size)
{
if (!initialized)
{
initPoolSize = size;
return;
}
else if (size > tatolTaskNum)
{
for (int i = tatolTaskNum; i < size && i < maxPoolSize; i++)
{
PooledThread thread = new PooledThread(this);
thread.start();
}
}
else if (size < tatolTaskNum)
{
while (getPoolSize() > size)
{
PooledThread th = (PooledThread)allThreads.get(0);
th.kill();
}
}
}
/** 获取所有线程集合的数量 */
public int getPoolSize()
{
return allThreads.size();
}
/** 创建一个新的线程并放入所有线程集合中 */
protected void threadCreated(PooledThread th)
{
synchronized (allThreads)
{
allThreads.add(th);
}
}
/** 从所有线程集合中删除一个线程 */
protected void threadDead(PooledThread th)
{
synchronized (allThreads)
{
// 如果空闲现成队列中还有引用,也清除掉。
threadIdleStateChange(th, false);
allThreads.remove(th);
}
}
/**
* <如果空闲现成队列中还有引用,也清除掉。>
*
* @param th 要操作的线程对象
* @param isIdle true:添加th、false:删除th
* @see [类、类#方法、类#成员]
*/
protected void threadIdleStateChange(PooledThread th, boolean isIdle)
{
synchronized (idleThreads)
{
if (isIdle)
{
idleThreads.add(th);
}
else
{
idleThreads.remove(th);
}
}
}
/**
* <获取一个空闲的线程> <功能详细描述>
* 如果没有空闲线程,可以新建并且目前的总线程数量不超过最大的线程数量则新建一个
*
* @param creatable 是否新建一个线程
* @return
* @see [类、类#方法、类#成员]
*/
public PooledThread getIdleThread(boolean creatable)
{
synchronized (idleThreads)
{
// idleThreads不为空说明有空闲线程
if (!idleThreads.isEmpty())
{
return (PooledThread)idleThreads.remove(0);
}
// 新建一个线程。
if (creatable && getPoolSize() < maxPoolSize)
{
PooledThread thread = new PooledThread(this);
thread.start();
return thread;
}
return null;
}
}
/**
* 获取一个运行任务,从任务队列集合中
*/
public ThreadTask getTaskToRun()
{
synchronized (tasksQueue)
{
if (tasksQueue.size() > 0)
return (ThreadTask)tasksQueue.remove(0);
else
return null;
}
}
/**
* <执行一个任务>
* <将任务放入任务队列集合,总任务书递增一,获取一个空闲线程,并激活启动>
*
* @param task
* @see [类、类#方法、类#成员]
*/
public void processTask(ThreadTask task)
{
synchronized (tasksQueue)
{
tasksQueue.add(task);
}
tatolTaskNum++;
// 默认的线程启动后都是等待状态,激活一个等待的闲置线程,让他自己去拿任务执行。
PooledThread th = getIdleThread(true);
if (th != null)
{
th.activeThread();
}
}
/**
* <利用一个线程执行一组任务>
* <功能详细描述>
*
* @param tasks
* @return
* @see [类、类#方法、类#成员]
*/
public boolean processTasksInSingleThread(ThreadTask[] tasks)
{
boolean isNewOrEmptyThreadToProcess = false;
// 获取一个空闲线程
PooledThread th = getIdleThread(true);
synchronized (tasksQueue)
{
if (th != null)
{
if (th.isTaskQueueEmpty()) // 有空线程可以立即执行任务。
{
isNewOrEmptyThreadToProcess = true;
th.putTasks(tasks);
// 如果是交给单个线程处理,线程池任务总是只加1,这些任务当成打包处理。
tatolTaskNum++;
}
else
{
tasksQueue.add(tasks);
// 如果没有交给单个线程,线程池任务数加上实际数量。
tatolTaskNum += tasks.length;
}
th.activeThread();
}
else
{
tasksQueue.add(tasks); // 暂时没有空线程来执行,先加入线程池任务队列中等待。
// 如果没有交给单个线程,线程池任务数加上实际数量。
tatolTaskNum += tasks.length;
}
}
return isNewOrEmptyThreadToProcess;
}
/** 任务结束:总的任务数量递减一 */
public void taskCompleted()
{
tatolTaskNum--;
}
/**
* <执行任务集合中的所有任务> <循环执行>
*
* @param tasks
* @see [类、类#方法、类#成员]
*/
public void taskReturnedFromThread(Vector tasks)
{
// 总的任务数量递减
tatolTaskNum--;
for (Iterator itr = tasks.iterator(); itr.hasNext();)
{
ThreadTask task = (ThreadTask)itr.next();
processTask(task);
}
}
/** 获取最大池数量 */
public int getMaxPoolSize()
{
return maxPoolSize;
}
}
--------------------------------------------------------------------接受线程池管理的线程------------------------------------------------------------------------------------------------------------------------------
package threadPoolImpl;
import java.util.Vector;
/**
* 接受线程池管理的线程
*/
@SuppressWarnings("unchecked")
public class PooledThread extends Thread
{
/** 线程任务集合 */
protected Vector tasks = new Vector();
/** 线程是否在运行 */
protected boolean running = false;
/** 线程是否停止运行 */
protected boolean stopped = false;
/** 线程是否挂起 */
protected boolean paused = false;
/** 线程是否被杀死 */
protected boolean killed = false;
/** 线程池对象 */
private ThreadPool pool;
/** 线程对象,在构造中创建一个线程放入线程池中 */
public PooledThread(ThreadPool pool)
{
this.pool = pool;
pool.threadCreated(this);
}
/** 将一个任务放入任务集合 */
public void putTask(ThreadTask task)
{
tasks.add(task);
}
/** 将一组任务放入任务集合 */
public void putTasks(ThreadTask[] tasks)
{
// 循环将单个任务放入任务集合
for (int i = 0; i < tasks.length; i++)
{
this.tasks.add(tasks[i]);
}
}
/** 从任务集合中取出第一个任务对象,如果任务集合中有任务则取出;没有则返回null */
protected ThreadTask popTask()
{
if (tasks.size() > 0)
return (ThreadTask)tasks.remove(0);
else
return null;
}
/** 判断线程是否在运行中 */
public boolean isRunning()
{
return running;
}
/** 判断任务集合是否为空,为空则返回true,否则返回false */
public boolean isTaskQueueEmpty()
{
return tasks.isEmpty();
}
/** 停止执行一个任务 */
public void stopTasks()
{
stopped = true;
}
/** 同步 */
public void stopTasksSync()
{
// 停止一个任务
stopTasks();
// 如果还在运行中,睡眠5毫秒
while (isRunning())
{
try
{
sleep(5);
}
catch (InterruptedException e)
{
}
}
}
/** 挂起一个线程任务 */
public void pauseTasks()
{
paused = true;
}
/** 同步挂起 */
public void pauseTasksSync()
{
pauseTasks();
while (isRunning())
{
try
{
sleep(5);
}
catch (InterruptedException e)
{
}
}
}
/** 杀死一个线程 */
public void kill()
{
if (!running)
interrupt();
else
killed = true;
}
/** 同步杀死 */
public void killSync()
{
kill();
while (isAlive())
{
try
{
sleep(5);
}
catch (InterruptedException e)
{
}
}
}
/** 激活一个线程 */
public synchronized void activeThread()
{
// 把线程从等待状态中激活,开始任务循环。
running = true;
pool.threadIdleStateChange(this, false);
this.notify();
}
public synchronized void run()
{
try
{
while (true)
{
// 处理控制线程命令先。
if (killed)
{
// 杀掉线程:向线程池任务队列转移自己所有任务,退出。
killed = false;
returnTaskToPool();
break;
}
if (stopped)
{
// 停止线程:向线程池任务队列转移自己所有任务,然后等待。
stopped = false;
returnTaskToPool();
running = false;
}
if (paused)
{
// 暂停线程,保持自己的任务队列,然后等待。
paused = false;
running = false;
}
ThreadTask task;
// 优先执行Thread自己的任务队列,再执行线程池中的任务队列。
if (running && (task = pool.getTaskToRun()) != null)
{
task.run();
pool.taskCompleted();
}
else if (running && (task = popTask()) != null)
{
task.run();
// 该线程的任务包执行完毕,表示线程池中的一个大任务包执行完成。
if (tasks.size() == 0)
{
pool.taskCompleted();
}
}
else
{
running = false;
pool.threadIdleStateChange(this, true);
this.wait();
}
}
}
catch (InterruptedException e)
{
// 在kill()方法中调用interrupt()方法,导致抛出此异常,结束线程。
// 非调试状态,注释掉让控制台输出clean
// e.printStackTrace();
return;
}
finally
{
returnTaskToPool();
tasks = null;
pool.threadDead(this);
}
}
/** 将任务放回线程池中,并清空任务集合 */
private void returnTaskToPool()
{
pool.taskReturnedFromThread(tasks);
tasks.clear();
}
}
----------------------------------------ThreadTask----(线程任务简单接口)--------- ------------------------------
package threadPoolImpl;
/**
* 线程任务
*/
public interface ThreadTask
{
public void run();
}
-------------------------------------------------------------ThreadTaskImpl----(线程任务简单接口实现)--------------------------------------------------------------------------------------------
package threadPoolImpl;
/**
* <线程任务实现类>
*/
public class ThreadTaskImpl implements ThreadTask
{
@Override
public void run()
{
System.out.println("执行一个任务");
}
}
-----------------------------------------------------------------------测试类-----------------------------------------------------------------------------
package threadPoolImpl;
/**
* <测试类>
*/
public class PoolThreadTest
{
public static void main(String[] args)
{
ThreadPool tp = new ThreadPool(10, 2);
// PooledThread phThread = new PooledThread(tp);
ThreadTask taskOne = new ThreadTaskImpl();
ThreadTask taskTwo = new ThreadTaskImpl();
// phThread.putTask(taskOne);
tp.processTask(taskOne);
tp.processTask(taskTwo);
}
}