最近寫了一個(gè) HTTP 代理服務(wù)器,發(fā)現(xiàn)訪問網(wǎng)頁(yè)時(shí)建立的連接很多,消耗的線程也非常的多,對(duì)于系統(tǒng)是
一個(gè)不小的開銷.而且這些線程存在的時(shí)間都很短,99%以上的線程存在的時(shí)間都在毫秒的等級(jí),相對(duì)來說
線程的建立的注銷就占了絕大部分的CPU時(shí)間.
因此,在網(wǎng)上搜了一下線程池的資料,發(fā)現(xiàn)里面的東西不是太大太復(fù)雜,就是寫得太爛,根本沒有一點(diǎn)專業(yè)
水準(zhǔn).
沒辦法,只好自己簡(jiǎn)單的學(xué)習(xí)了一下 wait()/notify()機(jī)制,寫了一個(gè)很小的線程池.
代碼如下(一共2個(gè)類):
/*
*一個(gè)簡(jiǎn)單的線程池 ThreadPool .java
*/
public class ThreadPool {
//以下是配置信息,可以更改
static int MAX_THREAD = 1000; //未使用
static int MIN_THREAD = 14;
static int id = 1; //線程 ID 號(hào),主要用于監(jiān)視線程的工作情況
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.size()<MIN_THREAD){
stack.push(wt);
return true;
} else {
return false;
}
}
synchronized public WorkThread getWorkThread() {
WorkThread wt = null;
if(stack.isEmpty()) {
wt = new WorkThread(this);
new Thread(wt,"線程ID:"+id).start();
id++;
} else {
wt = stack.pop();
}
return wt;
}
}
--------------------------------------------------------------------------
/*
*工作線程類 WorkThread.java
*/
public class WorkThread implements Runnable {
Object lock = new Object();
Runnable runner = null;
ThreadPool pool = null;
public WorkThread(ThreadPool pool) {
this.pool = pool;
}
public void start(Runnable r) {
runner = r;
synchronized(lock) {
lock.notify();
}
}
public void run() {
while(true) {
if(runner != null) {
runner.run();
runner = null; //及時(shí)回收資源
}
if(pool.putWorkThread(this)) {
System.out.println (Thread.currentThread().getName()+" 被回收!");
synchronized(lock) {
try {
lock.wait();
} catch (InterruptedException ie) {
System.out.println ("停止線程時(shí)出現(xiàn)異常");
}
}
} else {
System.out.println (Thread.currentThread().getName()+" 被丟棄!");
break;
}
}
}
}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注