import java.util.*;
import java.lang.reflect.Array;
/**
* Created by IntelliJ IDEA.
* User: Administrator
* Date: 2008-7-7
* Time: 9:07:56
* To change this template use File | Settings | File Templates.
*/
public class ThreadPool {
//初始化空闲队列以及工作队列
List freeThreads = new ArrayList();
List runThreads = new ArrayList();
//设置线程数量
private int size = 10;
//设置关闭条件语句
boolean runflag=true;
public synchronized void stopthread() {
runflag=false;
runThreads.clear();
Thread.interrupted();
}
public synchronized boolean getrunflag(){
return runflag;
}
//线程池初始化
public ThreadPool(int size) {
this.size = size;
init();
}
public ThreadPool() {
init();
}
//添加线程
private void init() {
for (int i = 0; i < size; i++) {
try{
MyThread thread = new MyThread(this, i);
new Thread(thread).start();
freeThreads.add(thread);
try {
Thread.sleep(100);
} catch (Exception e) {}
}catch(Exception f){}
}
}
// 运行线程
public synchronized void runTask(Runnable task) {
MyThread thread = (MyThread) freeThreads.remove(0);
runThreads.add(thread);
thread.setTask(task);
}
//释放线程
public synchronized void free(MyThread thread) {
runThreads.remove(thread);
freeThreads.add(thread);
}
//显性显示信息
public synchronized void print() {
System.out.println("num:" + size);
System.out.println("free: " + freeThreads.size());
System.out.println(freeThreads);
System.out.println("run: " + runThreads.size());
System.out.println(runThreads);
}
//进行任务的线程
public class MyThread implements Runnable {
private ThreadPool pool;
private Runnable task = null;
private long start;
private long end;
private int num;
private int sum = 0;
public MyThread(ThreadPool pool, int num) {
this.pool = pool;
this.num = num;
}
//运行任务
public void run() {
while (getrunflag()) {
start = System.currentTimeMillis();
try {
if (task == null) {
this.wait();
}
task.run();
task = null;
pool.free(this);
end = System.currentTimeMillis();
sum += (end - start);
getTime();
} catch (Exception e) { }
}
}
public synchronized void setTask(Runnable task) {
this.task = task;
notifyAll();
}
//显示工作线程
public String toString() {
return "Thread: " + num;
}
//获取时间
public void getTime() {
System.out.println(this + "\nTime:" + (end - start) + "s\nSum:" + sum);
}
}
//测试
public static void main(String[] args) throws Exception {
ThreadPool pool = new ThreadPool();
pool.runTask(new Runnable() {
public void run() {
System.out.println("thread run No.1");
}
});
pool.print();
pool.runTask(new Runnable() {
public void run() {
System.out.println("thread run No.2");
}
});
pool.print();
pool.runTask(new Runnable() {
public void run() {
System.out.println("thread run No.3");
}
});
pool.print();
//关闭线程池
pool.stopthread();
}
}