package threadpool;
import java.util.Vector;
import org.omg.PortableServer.THREAD_POLICY_ID;
public class ThreadPoolManger {
private int maxThread;
public Vector vector; // Vector类实现可增长的对象数组
private MyNotify notify;
public void setMaxThread(int threadCount) {
this.maxThread = threadCount;
}
public ThreadPoolManger(int threadCount, MyNotify notify) {
this.notify = notify;
this.setMaxThread(threadCount);
System.out.println("线程池开始运行了...");
vector = new Vector();
for (int i = 1; i <= threadCount; i++) {
SimpleThread thread = new SimpleThread(i, this.notify);
vector.addElement(thread); // 将指定的组件添加到此向量的末尾,将其大小增加1
thread.start();
}
}
public void process(Taskable task) {
int i;
for (i = 0; i < vector.size(); i++) {
SimpleThread curretThread = (SimpleThread) vector.elementAt(i); // 返回指定索引处的组件
if (!curretThread.isRunning()) {
System.out.println("Thread " + (i + 1) + "执行新任务了");
curretThread.setTask(task);
curretThread.setRunning(true);
return;
}
}
System.out.println("=======================");
System.out.println("线程池中没有空闲的线程");
System.out.println("=======================");
if (i == vector.size()) {
int temp = maxThread;
this.setMaxThread(maxThread + 10);
for (int j = temp + 1; j <= maxThread; j++) {
SimpleThread thread = new SimpleThread(j, this.notify);
vector.addElement(thread);
thread.start();
}
// 创建完之后需要重新执行process
this.process(task);
}
}
}
package threadpool;
//任务接口
public interface Taskable {
public Object doTask();
}
package threadpool;
//通知接口:用于通知主线程,任务线程已经运行完了,有结果了
public interface MyNotify {
public void notifyResult(Object result);
}
package threadpool;
public class SimpleThread extends Thread {
private boolean runningFlag; // 运行的状态 默认为false
private Taskable task; // 要执行的操作
private int threadNumber; // 线程的编号
private MyNotify myNotify; // 通知接口
// 标志runningFlag用以激活线程
public boolean isRunning() {
return this.runningFlag;
}
public synchronized void setRunning(boolean flag) {
this.runningFlag = flag; // 设置当前线程为true,表示当前线程已经被占用
if (flag) {
this.notifyAll(); // 唤醒其他线程就绪
}
}
public Taskable getTask() {
return task;
}
public void setTask(Taskable task) {
this.task = task;
}
// 提示哪个线程工作
public SimpleThread(int threadNumber, MyNotify notify) {
runningFlag = false;
this.threadNumber = threadNumber;
System.out.println("Thread " + threadNumber + " started.");
this.myNotify = notify;
}
public synchronized void run() {
try {
while (true) {
if (!runningFlag) { // 无线循环
this.wait(); // 判断标志位是否为true,如果runningFlag为false,等待调度?
} else {
System.out.println("线程" + threadNumber + "开始执行任务");
Object returnValue = this.task.doTask();
if (myNotify != null) {
myNotify.notifyResult(returnValue);
}
sleep(5000);
System.out.println("线程" + threadNumber + "重新准备...");
setRunning(false);
}
}
} catch (InterruptedException e) {
System.out.println("Interrupt");
}
}
}