Java實現(xiàn)通用線程池_第1頁
Java實現(xiàn)通用線程池_第2頁
Java實現(xiàn)通用線程池_第3頁
Java實現(xiàn)通用線程池_第4頁
Java實現(xiàn)通用線程池_第5頁
已閱讀5頁,還剩9頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

1、Java實現(xiàn)通用線程池線程池通俗的描述就是預(yù)先創(chuàng)建若干空閑線程,等到需要用多線程去處理事務(wù)的時候去喚醒某些空閑線程執(zhí)行處理任務(wù),這樣就省去了頻繁創(chuàng)建線程的時間,因為頻 繁創(chuàng)建線程是要耗費大量的CPU資源的。如果一個應(yīng)用程序需要頻繁地處理大量并發(fā)事務(wù),不斷的創(chuàng)建銷毀線程往往會大大地降低系統(tǒng)的效率,這時候線程池就派 上用場了。本文旨在使用Java語言編寫一個通用的線程池。當需要使用線程池處理事務(wù)時,只需按照指定規(guī)范封裝好事務(wù)處理對象,然后用已有的線程池對象去自動選擇空 閑線程自動調(diào)用事務(wù)處理對象即可。并實現(xiàn)線程池的動態(tài)修改(修改當前線程數(shù),最大線程數(shù)等)。下面是實現(xiàn)代碼:/ThreadTask .

2、javapackage polarman.threadpool;/* 線程任務(wù)* author ryang* 2006-8-8*/public interface ThreadTask public void run(;/PooledThread.javapackage polarman.threadpool;/* 接受線程池管理的線程* author ryang* 2006-8-8*/public class PooledThread extends Thread protected Vector tasks = new Vector(;protected boolean running =

3、 false;protected boolean stopped = false;protected boolean paused = false;protected boolean killed = false;private ThreadPool pool;public PooledThread(ThreadPool poolthis.pool = pool;public void putTask(ThreadTask tasktasks.add(task;public void putTasks(ThreadTask tasksfor(int i=0; i public void put

4、Tasks(Collection tasksprotected ThreadTask popTask(if(tasks.size( > 0return (ThreadTasktasks.remove(0;elsereturn null;public boolean isRunning(return running;public void stopTasks(stopped = true;public void stopTasksSync(stopTasks(;while(isRunning(try sleep(5; catch (InterruptedException e public

5、 void pauseTasks(paused = true;public void pauseTasksSync(pauseTasks(;while(isRunning(try sleep(5; catch (InterruptedException e public void kill(if(!runninginterrupt(;elsekilled = true;public void killSync(kill(;while(isAlive(try sleep(5; catch (InterruptedException e public synchronized void start

6、Tasks(running = true;this.notify(;public synchronized void run(trywhile(trueif(!running | tasks.size( = 0pool.notifyForIdleThread(;this.wait(;elseThreadTask task;while(task = popTask( != nulltask.run(;if(stoppedstopped = false;if(tasks.size( > 0tasks.clear(;break;if(pausedpaused = false;if(tasks.

7、size( > 0break;running = false;if(killedkilled = false;break;catch(InterruptedException ereturn;/ThreadPool.javapackage polarman.threadpool;/* 線程池* author ryang* 2006-8-8*/public class ThreadPool protected int maxPoolSize;protected int initPoolSize;protected Vector threads = new Vector(;protected

8、 boolean initialized = false;protected boolean hasIdleThread = false;public ThreadPool(int maxPoolSize, int initPoolSizethis.maxPoolSize = maxPoolSize;this.initPoolSize = initPoolSize;public void init(initialized = true;for(int i=0; i PooledThread thread = new PooledThread(this;thread.start(;threads

9、.add(thread;public void setMaxPoolSize(int maxPoolSizethis.maxPoolSize = maxPoolSize;if(maxPoolSize < getPoolSize(setPoolSize(maxPoolSize;/* 重設(shè)當前線程數(shù)* 若需殺掉某線程,線程不會立刻殺掉,而會等到線程中的事務(wù)處理完成* 但此方法會立刻從線程池中移除該線程,不會等待事務(wù)處理結(jié)束* param size*/public void setPoolSize(int sizeif(!initializedinitPoolSize = size;retur

10、n;else if(size > getPoolSize(for(int i=getPoolSize(; i PooledThread thread = new PooledThread(this;thread.start(;threads.add(thread;else if(size < getPoolSize(while(getPoolSize( > sizePooledThread th = (PooledThreadthreads.remove(0;th.kill(;public int getPoolSize(return threads.size(;protec

11、ted void notifyForIdleThread(hasIdleThread = true;protected boolean waitForIdleThread(hasIdleThread = false;while(!hasIdleThread && getPoolSize( >= maxPoolSizetry Thread.sleep(5; catch (InterruptedException e return false;return true;public synchronized PooledThread getIdleThread(while(tr

12、uefor(Iterator itr=threads.iterator(; itr.hasNext(;PooledThread th = (PooledThreaditr.next(;if(!th.isRunning(return th;if(getPoolSize( < maxPoolSizePooledThread thread = new PooledThread(this;thread.start(;threads.add(thread;return thread;if(waitForIdleThread( = falsereturn null;public void proce

13、ssTask(ThreadTask taskPooledThread th = getIdleThread(;if(th != nullth.putTask(task;th.startTasks(;public void processTasksInSingleThread(ThreadTask tasksPooledThread th = getIdleThread(;if(th != nullth.putTasks(tasks;th.startTasks(;public void processTasksInSingleThread(Collection tasksPooledThread

14、 th = getIdleThread(;if(th != nullth.putTasks(tasks;th.startTasks(;下面是線程池的測試程序/ThreadPoolTest.javapublic class ThreadPoolTest public static void main(String args final ThreadPool pool = new ThreadPool(3, 2;pool.init(;Thread cmdThread = new Thread(public void run(BufferedReader reader = new BufferedR

15、eader(new InputStreamReader(System.in;while(truetry String line = reader.readLine(;String words = line.split(" "if(words0.equalsIgnoreCase("quit"System.exit(0;else if(words0.equalsIgnoreCase("size" && words.length >= 2tryint size = Integer.parseInt(words1;poo

16、l.setPoolSize(size;catch(Exception eelse if(words0.equalsIgnoreCase("max" && words.length >= 2tryint max = Integer.parseInt(words1;pool.setMaxPoolSize(max;catch(Exception eelse if(words0.equalsIgnoreCase("task" && words.length >= 3tryint timelen = Integer.pa

17、rseInt(words2;SimpleTask task = new SimpleTask(words1, timelen * 1000;cessTask(task;catch(Exception e catch (IOException e e.printStackTrace(;cmdThread.start(;/*for(int i=0; i<10; i+SimpleTask task = new SimpleTask("Task" + i, (i+10*1000;cessTask(task;*/class SimpleTask implements ThreadTaskprivate String taskName;private int timeLen;public SimpleTask(String taskName, int timeLenthis.taskName = taskName;this.timeLen = timeLen;public void run( ": START TASK "" + taskName + """try Thread.sleep(timeLen;

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論