一個很小的線程池
代碼如下(一共
/*
*一個簡單的線程池 ThreadPool
*/
public class ThreadPool {
//以下是配置信息
static int MAX_THREAD =
static int MIN_THREAD =
static int id =
static private ThreadPool pool = new ThreadPool();
static public ThreadPool getThreadPool() {
return pool;
}
Stack<WorkThread> stack = new Stack<WorkThread>(MIN_THREAD);
private ThreadPool() {
}
synchronized public boolean putWorkThread(WorkThread wt) {
if(stack
stack
return true;
} else {
return false;
}
}
synchronized public WorkThread getWorkThread() {
WorkThread wt = null;
if(stack
wt = new WorkThread(this);
new Thread(wt
id++;
} else {
wt = stack
}
return wt;
}
}
/*
*工作線程類 WorkThread
*/
public class WorkThread implements Runnable {
Object lock = new Object();
Runnable runner = null;
ThreadPool pool = null;
public WorkThread(ThreadPool pool) {
this
}
public void start(Runnable r) {
runner = r;
synchronized(lock) {
lock
}
}
public void run() {
while(true) {
if(runner != null) {
runner
runner = null; //及時回收資源
}
if(pool
System
synchronized(lock) {
try {
lock
} catch (InterruptedException ie) {
System
}
}
} else {
System
break;
}
}
}
}
使用方法:
Runnable r =
new Thread(r)
這是你以前的代碼
ThreadPool
就可以了
這個線程池還有兩個功能沒有實現
但這個線程池也有一個好處
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27725.html