日期:2014-05-20  浏览次数:20836 次

调用线程池中一个方法,传递给线程池一个task,获取执行的线程
import java.util.LinkedList;

import cn.com.gei.kmp4.core.task.entity.Task;

public class ThreadPoolTest extends ThreadGroup {
public static final int Max_Threads = 15;
/** 线程池中所容纳的线程数量 */
public static final int MAX_RUNNING_TASK = 15;
/** 线程池中所能处理的任务数 */
private LinkedList queueTasks;
/** 任务队列 */
private PoolWorker[] threads;
/** 线程池中的线程数组 */
private boolean isClosed = false;

/** 线程池是否关闭 */
public ThreadPoolTest(String name) {
super(name);
// TODO Auto-generated constructor stub
queueTasks = new LinkedList<Task>();
/** 初始化线程池中的线程能处理的任务队列 */
for (int i = 0; i < Max_Threads; i++) {
/** 创建线程 */
threads[i] = new PoolWorker();
threads[i].start();
}

}
public Thread getThread(Task task){
/** 外界传递给线程池,获取一个线程*/
return null;
}

/** 向任务队列中加入一个新任务,由任务线程去执行该任务 */
public synchronized void addTask(Task task) {
if (isClosed) {
throw new IllegalStateException();
}
if (task != null) {
queueTasks.add(task);
/** 向队列中加入一个任务 */
notify();
/** 唤醒一个正在getTask()方法中待任务的任务线程 */
}
}

/** 从任务队列中取出一个任务,任务线程会调用此方法 */
private synchronized Task getTask() throws InterruptedException {
while (queueTasks.size() == 0) {
if (isClosed)
return null;
wait();
/** 如果工作队列中没有任务,就等待任务 */
}
return (Task) queueTasks.removeFirst();
/** 反回队列中第一个元素,并从队列中删除 */
}

/** 等待任务线程把所有任务执行完毕 */
public void waitFinish() {
synchronized (this) {
isClosed = true;
notifyAll();
/** 唤醒所有还在getTask()方法中等待任务的工作线程 */
}
Thread[] threads = new Thread[activeCount()];
/** activeCount() 返回该线程组中活动线程的估计值。 */
int count = enumerate(threads);
/** enumerate()方法继承自ThreadGroup类,根据活动线程的估计值获得线程组中当前所有活动的工作线程 */
for (int i = 0; i < count; i++) {
/** 等待所有工作线程结束 */
try {
threads[i].join();
/** 等待工作线程结束 */
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}

/** 关闭线程池 */
public synchronized void closePool() {
if (!isClosed) {
waitFinish();
/** 等待任务线程执行完毕 */
isClosed = true;
queueTasks.clear();
/** 清空任务队列 */
interrupt();
/** 中断线程池中的所有的任务线程,此方法继承自ThreadGroup类 */
}
}

/** 任务线程类,负责从任务队列中取出任务,并执行 */
private class PoolWorker extends Thread {
/** 该工作线程是否有效 */
private boolean isRunning = true;
/** 该工作线程是否可以执行新任务 */
private boolean isWaiting = true;

public void stopWorker() {
this.isRunning = false;
}

public boolean isWaiting() {
return this.isWaiting;
}

public void run() {
while (!isClosed && isRunning) {
Task r = null;
synchronized (queueTasks) {
while (queueTasks.isEmpty()) {
try {
/** 任务队列为空,则等待有新任务加入从而被唤醒 */
queueTasks.wait(20);
} catch (Exception ie) {
ie.printStackTrace();
}
}
/** 取出任务执行 */
try {
r = getTask();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (r == null)
return;
try {

/** 运行任务 */ 
/**不知道做什么*/
} catch (Throwable t) {
t.printStackTrace();
}

}

}
}
}

}

------解决方案--------------------
这种代码的排版让人就直接不太想看你的代码了。