![Java實現(xiàn)通用線程池_第1頁](http://file3.renrendoc.com/fileroot_temp3/2022-1/13/2768b7e4-2559-472f-a2e7-6502e1e0fbbc/2768b7e4-2559-472f-a2e7-6502e1e0fbbc1.gif)
![Java實現(xiàn)通用線程池_第2頁](http://file3.renrendoc.com/fileroot_temp3/2022-1/13/2768b7e4-2559-472f-a2e7-6502e1e0fbbc/2768b7e4-2559-472f-a2e7-6502e1e0fbbc2.gif)
![Java實現(xiàn)通用線程池_第3頁](http://file3.renrendoc.com/fileroot_temp3/2022-1/13/2768b7e4-2559-472f-a2e7-6502e1e0fbbc/2768b7e4-2559-472f-a2e7-6502e1e0fbbc3.gif)
![Java實現(xiàn)通用線程池_第4頁](http://file3.renrendoc.com/fileroot_temp3/2022-1/13/2768b7e4-2559-472f-a2e7-6502e1e0fbbc/2768b7e4-2559-472f-a2e7-6502e1e0fbbc4.gif)
![Java實現(xiàn)通用線程池_第5頁](http://file3.renrendoc.com/fileroot_temp3/2022-1/13/2768b7e4-2559-472f-a2e7-6502e1e0fbbc/2768b7e4-2559-472f-a2e7-6502e1e0fbbc5.gif)
版權(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. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- Unit3 Weather A let's learn(說課稿)-2023-2024學(xué)年人教PEP版英語四年級下冊001
- 2025寫場地租賃合同范文
- 2025工程建設(shè)招標投標合同履約銀行保證書
- Unit 1 Playtime Lesson 3(說課稿)-2023-2024學(xué)年人教新起點版英語二年級下冊
- 2023九年級歷史下冊 第一單元 殖民地人民的反抗與資本主義制度的擴展第3課 美國內(nèi)戰(zhàn)說課稿 新人教版
- 2025泵車租賃合同
- 2024-2025學(xué)年高中歷史 專題二 近代中國資本主義的曲折發(fā)展 2.1 近代中國民族工業(yè)的興起說課稿1 人民版必修2
- 蔬菜物資發(fā)放方案
- 養(yǎng)生館前臺合同范例
- 代理經(jīng)營店鋪合同范例
- 九年級短跑2 公開課教學(xué)設(shè)計
- 平衡計分卡-化戰(zhàn)略為行動
- 幼兒園小班下學(xué)期期末家長會PPT模板
- 礦山安全培訓(xùn)課件-地下礦山開采安全技術(shù)
- 【課件】DNA片段的擴增及電泳鑒定課件高二下學(xué)期生物人教版(2019)選擇性必修3
- GB/T 6417.1-2005金屬熔化焊接頭缺欠分類及說明
- 2023年湖北成人學(xué)位英語考試真題及答案
- 《社會主義市場經(jīng)濟理論(第三版)》第七章社會主義市場經(jīng)濟規(guī)則論
- 《腰椎間盤突出》課件
- simotion輪切解決方案與應(yīng)用手冊
- 柴油發(fā)電機運行檢查記錄表格
評論
0/150
提交評論