菲姐-进程池
package bao;
import java.util.LinkedList;
public class mythdread extends ThreadGroup{
private boolean isActive;
private static int threadPoolID;
private LinkedList taskQueue;
private int threadID;
public mythdread(int numThreads) {
super("ThreadPool-" + (threadPoolID++));
// TODO Auto-generated constructor stub
setDaemon(true); //设置为后台运行,一个守护进程。只有在main结束时结束
isActive = true; //很重要
taskQueue = new LinkedList(); //存Threads
for (int i=0; i<numThreads; i++) { //生成系统中真正的运行线程。
new PooledThread().start();
}
}
protected synchronized Runnable getTask() //需要同步别拿乱了。两个跑的Thread 拿了同一个task
throws InterruptedException{
while(taskQueue.size() == 0){
if(!isActive){ //如果池是死的,拿不到。
return null;
}
wait(); //要不然,就等着:此线程卡死这,停了。直到有“人” notify()了。才有机会在跑起来。
}
return (Runnable)taskQueue.removeFirst();
}
protected synchronized void addTask(Runnable task) {
if (!isActive) {
throw new IllegalStateException();
}
if (task != null) {
taskQueue.add(task);
notify(); //加了一个,就告诉那边,有要的来拿。
}
}
public void join() { //确保每个线程都完成
synchronized (this) { //确保霸占,以防万一有人改
isActive = false;
notifyAll();
}
Thread[] threads = new Thread[activeCount()];
int count = enumerate(threads);
for (int i=0; i<count; i++) {
try {
threads[i].join();
}
catch (InterruptedException ex) { }
}
}
public synchronized void close() {
if (isActive) {
isActive = false;
taskQueue.clear();
interrupt();
}
}
private class PooledThread extends Thread {
public PooledThread() { //生成进程名
super(mythdread.this,
"PooledThread-" + (threadID++));
}
public void run() {
while (!isInterrupted()) {
// get a task to run
Runnable task = null;
try {
task = getTask();
}
catch (InterruptedException ex) { }
// if getTask() returned null or was interrupted,
// close this thread by returning.
if (task == null) {
return;
}
// run the task, and eat any exceptions it throws
try {
task.run();
}
catch (Throwable t) {
uncaughtException(this, t);
}
}
}
}
}