package com.spreadcomm.game.net;
import java.util.LinkedList;
import java.util.List;
class ThreadManager {
/**Working thread object in this pool*/
private ExecuteThread[] mWorkThreadQueue;
/**Save the user thread, which implement by user*/
private List<Runnable> mWaitingQueue = new LinkedList<Runnable> ();
/**Indicate the pool life cycle*/
private boolean mIsActive = true;
/**Control waiting queue thread safely*/
private Object mTicket = new Object();
/**
* Default only one working thread in this pool
* @param name
*/
public ThreadManager(String name){
this(name,1);
}
/**
* Create working thread queue, according to special account
*
* @param name
* @param threadcount
*/
public ThreadManager(String name, int threadcount) {
mWorkThreadQueue = new ExecuteThread[threadcount];
for (int i = 0; i < mWorkThreadQueue.length; i++) {
mWorkThreadQueue[i] = new ExecuteThread(name, this, i);
mWorkThreadQueue[i].setDaemon(true);
mWorkThreadQueue[i].start();
}
// when virtual machine is idle state, it will been invoke
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
if (mIsActive) {
shutdown();
}
}
});
}
/**
* push thread to waiting queue
* @param task
*/
public synchronized void invokeLater(Runnable task) {
synchronized (mWaitingQueue) {
mWaitingQueue.add(task);
}
synchronized (mTicket) {
mTicket.notify();
}
}
/**
* poll thread in waiting queue
*
* @return
*/
public Runnable poll(){
while(mIsActive){
synchronized(mWaitingQueue){
if (mWaitingQueue.size() > 0) {
Runnable task = mWaitingQueue.remove(0);
if (null != task) {
return task;
}
}
}
synchronized (mTicket) {
try {
mTicket.wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
return null;
}
/**
* Release all of working thread
*/
public synchronized void shutdown() {
if (mIsActive) {
mIsActive = false;
for (ExecuteThread thread : mWorkThreadQueue) {
thread.shutdown();
}
synchronized (mTicket) {
mTicket.notify();
}
} else {
throw new IllegalStateException("Already shutdown");
}
}
}
/**
* This is a work thread, replay to read waiting
* queue and run it until it is done
*
* @author
*
*/
class ExecuteThread extends Thread {
ThreadManager mThreadPoolManager;
private boolean mAlive = true;
ExecuteThread(String name, ThreadManager q, int index) {
super(name + "[" + index + "]");
mThreadPoolManager = q;
}
public void shutdown() {
mAlive = false;
}
/**
* Get waiting thread from waiting queue
*/
public void run() {
while (mAlive) {
Runnable task = mThreadPoolManager.poll();
if (null != task) {
try {
task.run();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
一个简单的JAVA线程池实例
最新推荐文章于 2024-10-06 20:16:20 发布