/**
* Filename: ThreadPool.java
*
* @Copyright: Copyright (c)2013 Company:
*
* @author:
* @version: 1.0 Create at: 2013-11-4 上午09:25:08
*/
public class ThreadPool extends ThreadGroup {
private boolean isClosed = false;
private static ThreadPool threadPool;
private static LinkedList<Runnable> workQueue;
// 启动线程池中的线程
private ThreadPool(Integer poolSize) {
super(new Date().getTime() + ":" + threadPool);
workQueue = new LinkedList<Runnable>();
for (int i = 0; i < poolSize; i++) {
new WorkThread(i).start();
}
try {
Thread.sleep(2000); // 线程池准备线程
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //
}
// 初始化单列模式线程池
public static ThreadPool getInstance() {
if (threadPool == null)
threadPool = new ThreadPool(50);
return threadPool;
}
public synchronized void execute(Runnable task) {
if (task != null ) {
try {
workQueue.add(task);
System.out.println("execute task.....");
notify();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private synchronized Runnable getTask(int threadid) throws InterruptedException {
while (workQueue.size() == 0) {
if (isClosed)
return null;
System.out.println("work thread--------" + threadid + " wait");
wait(threadid);
}
System.out.println("work thread--------" + threadid + " run");
return workQueue.removeFirst();
}
/*
* 关闭线程池
*/
public synchronized void closePool() {
if (!isClosed) {
waitFinish(); // 等待工作线程执行完毕
isClosed = true;
System.out.println("thread is over........");
workQueue.clear(); // 清空工作队列
interrupt(); // 中断线程池中的所有的工作线程,此方法继承自ThreadGroup类
}
}
/**
* 等待所有线程运行完毕
*/
public void waitFinish() {
synchronized (this) {
isClosed = true;
notifyAll();
}
Thread[] threads = new Thread[activeCount()]; // 已激活处于等待中的线程
int count = enumerate(threads);
for (int i = 0; i < count; i++) {
try {
threads[i].join(); // 等待所有线程执行完毕
} catch (Exception e) {
e.printStackTrace();
}
}
}
private class WorkThread extends Thread {
private int id;
private WorkThread(int id) {
super(ThreadPool.this, id + "");
this.id = id;
}
public void run() {
while (!isInterrupted()) {
Runnable task = null;
try {
task = getTask(id);
if (task == null)
return;
task.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}