public class ThreadPool {
/**
* 任务队列,将,要执行的所有任务放到队列里,等线程池里边的线程有空闲时再继续执行任务。
* @author Administrator
*/
private final static Logger LOG = LogManager.getLogger(ThreadPool.class);
private final PoolTask[] threads;
private final BlockingQueue<Object> queue;
private final Random rand = new Random();
public ThreadPool(int nThreads){
queue = new LinkedBlockingQueue<Object>();
threads = new PoolTask[nThreads];
for (int i=0; i<nThreads; i++){
threads[i] = new PoolTask();
threads[i].start();
}
}
public void execute(Runnable r) {
int i = rand.nextInt(threads.length);
threads[i].execute(r);
}
public void quitQueue() {
for (int i = 0; i < threads.length; i++) {
threads[i].execute(new EmptyTask());
}
for (int i = 0; i < threads.length; i++) {
try {
threads[i].join();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private class PoolTask extends Thread {
public void execute(Runnable r) {
try {
queue.put(r);
} catch (InterruptedException e) {
LOG.debug("任务添加失败!", e);
}
}
public void run() {
Runnable r = null;
while (true) {
try {
r = (Runnable)queue.take();
} catch (InterruptedException e) {
LOG.debug("获取任务失败!", e);
}
try {
r.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(r instanceof EmptyTask) {
break;
}
}
}
}
}
public class EmptyTask implements Runnable {
public void run() {}
}
}
调用的时候:
ThreadPool threadPool = new ThreadPool(THREAD_COUNT);
//处理业务逻辑线程
ConnectMember conMember=new ConnectMember();
conMember.setInit(sessionId, req, out);
threadPool.execute(conMember);
threadPool.quitQueue();//取消队列任务