Java通過Executors提供四種線程池

http://cuisuqiang.iteye.com/blog/2019372

Java通過Executors提供四種線程池,分別為:
newCachedThreadPool創建一個可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則新建線程。
newFixedThreadPool 創建一個定長線程池,可控制線程最大并發數,超出的線程會在隊列中等待。
newScheduledThreadPool 創建一個定長線程池,支持定時及周期性任務執行。
newSingleThreadExecutor 創建一個單線程化的線程池,它只會用唯一的工作線程來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先級)執行。

?

(1) newCachedThreadPool
創建一個可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則新建線程。示例代碼如下:

Java代碼 ?收藏代碼
  1. package?test;??
  2. import?java.util.concurrent.ExecutorService;??
  3. import?java.util.concurrent.Executors;??
  4. public?class?ThreadPoolExecutorTest?{??
  5. ?public?static?void?main(String[]?args)?{??
  6. ??ExecutorService?cachedThreadPool?=?Executors.newCachedThreadPool();??
  7. ??for?(int?i?=?0;?i?<?10;?i++)?{??
  8. ???final?int?index?=?i;??
  9. ???try?{??
  10. ????Thread.sleep(index?*?1000);??
  11. ???}?catch?(InterruptedException?e)?{??
  12. ????e.printStackTrace();??
  13. ???}??
  14. ???cachedThreadPool.execute(new?Runnable()?{??
  15. ????public?void?run()?{??
  16. ?????System.out.println(index);??
  17. ????}??
  18. ???});??
  19. ??}??
  20. ?}??
  21. }??

?

線程池為無限大,當執行第二個任務時第一個任務已經完成,會復用執行第一個任務的線程,而不用每次新建線程。
?
(2) newFixedThreadPool
創建一個定長線程池,可控制線程最大并發數,超出的線程會在隊列中等待。示例代碼如下:

Java代碼 ?收藏代碼
  1. package?test;??
  2. import?java.util.concurrent.ExecutorService;??
  3. import?java.util.concurrent.Executors;??
  4. public?class?ThreadPoolExecutorTest?{??
  5. ?public?static?void?main(String[]?args)?{??
  6. ??ExecutorService?fixedThreadPool?=?Executors.newFixedThreadPool(3);??
  7. ??for?(int?i?=?0;?i?<?10;?i++)?{??
  8. ???final?int?index?=?i;??
  9. ???fixedThreadPool.execute(new?Runnable()?{??
  10. ????public?void?run()?{??
  11. ?????try?{??
  12. ??????System.out.println(index);??
  13. ??????Thread.sleep(2000);??
  14. ?????}?catch?(InterruptedException?e)?{??
  15. ??????e.printStackTrace();??
  16. ?????}??
  17. ????}??
  18. ???});??
  19. ??}??
  20. ?}??
  21. }??

?
因為線程池大小為3,每個任務輸出index后sleep 2秒,所以每兩秒打印3個數字。
定長線程池的大小最好根據系統資源進行設置。如Runtime.getRuntime().availableProcessors()

?

(3)? newScheduledThreadPool
創建一個定長線程池,支持定時及周期性任務執行。延遲執行示例代碼如下:

Java代碼 ?收藏代碼
  1. package?test;??
  2. import?java.util.concurrent.Executors;??
  3. import?java.util.concurrent.ScheduledExecutorService;??
  4. import?java.util.concurrent.TimeUnit;??
  5. public?class?ThreadPoolExecutorTest?{??
  6. ?public?static?void?main(String[]?args)?{??
  7. ??ScheduledExecutorService?scheduledThreadPool?=?Executors.newScheduledThreadPool(5);??
  8. ??scheduledThreadPool.schedule(new?Runnable()?{??
  9. ???public?void?run()?{??
  10. ????System.out.println("delay?3?seconds");??
  11. ???}??
  12. ??},?3,?TimeUnit.SECONDS);??
  13. ?}??
  14. }??

?
表示延遲3秒執行。

定期執行示例代碼如下:

Java代碼 ?收藏代碼
  1. package?test;??
  2. import?java.util.concurrent.Executors;??
  3. import?java.util.concurrent.ScheduledExecutorService;??
  4. import?java.util.concurrent.TimeUnit;??
  5. public?class?ThreadPoolExecutorTest?{??
  6. ?public?static?void?main(String[]?args)?{??
  7. ??ScheduledExecutorService?scheduledThreadPool?=?Executors.newScheduledThreadPool(5);??
  8. ??scheduledThreadPool.scheduleAtFixedRate(new?Runnable()?{??
  9. ???public?void?run()?{??
  10. ????System.out.println("delay?1?seconds,?and?excute?every?3?seconds");??
  11. ???}??
  12. ??},?1,?3,?TimeUnit.SECONDS);??
  13. ?}??
  14. }??

?
表示延遲1秒后每3秒執行一次。

?

(4) newSingleThreadExecutor
創建一個單線程化的線程池,它只會用唯一的工作線程來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先級)執行。示例代碼如下:

Java代碼 ?收藏代碼
  1. package?test;??
  2. import?java.util.concurrent.ExecutorService;??
  3. import?java.util.concurrent.Executors;??
  4. public?class?ThreadPoolExecutorTest?{??
  5. ?public?static?void?main(String[]?args)?{??
  6. ??ExecutorService?singleThreadExecutor?=?Executors.newSingleThreadExecutor();??
  7. ??for?(int?i?=?0;?i?<?10;?i++)?{??
  8. ???final?int?index?=?i;??
  9. ???singleThreadExecutor.execute(new?Runnable()?{??
  10. ????public?void?run()?{??
  11. ?????try?{??
  12. ??????System.out.println(index);??
  13. ??????Thread.sleep(2000);??
  14. ?????}?catch?(InterruptedException?e)?{??
  15. ??????e.printStackTrace();??
  16. ?????}??
  17. ????}??
  18. ???});??
  19. ??}??
  20. ?}??
  21. }??

?
結果依次輸出,相當于順序執行各個任務。

你可以使用JDK自帶的監控工具來監控我們創建的線程數量,運行一個不終止的線程,創建指定量的線程,來觀察:
工具目錄:C:\Program Files\Java\jdk1.6.0_06\bin\jconsole.exe
運行程序做稍微修改:

Java代碼 ?收藏代碼
  1. package?test;??
  2. import?java.util.concurrent.ExecutorService;??
  3. import?java.util.concurrent.Executors;??
  4. public?class?ThreadPoolExecutorTest?{??
  5. ?public?static?void?main(String[]?args)?{??
  6. ??ExecutorService?singleThreadExecutor?=?Executors.newCachedThreadPool();??
  7. ??for?(int?i?=?0;?i?<?100;?i++)?{??
  8. ???final?int?index?=?i;??
  9. ???singleThreadExecutor.execute(new?Runnable()?{??
  10. ????public?void?run()?{??
  11. ?????try?{??
  12. ??????while(true)?{??
  13. ???????System.out.println(index);??
  14. ???????Thread.sleep(10?*?1000);??
  15. ??????}??
  16. ?????}?catch?(InterruptedException?e)?{??
  17. ??????e.printStackTrace();??
  18. ?????}??
  19. ????}??
  20. ???});??
  21. ???try?{??
  22. ????Thread.sleep(500);??
  23. ???}?catch?(InterruptedException?e)?{??
  24. ????e.printStackTrace();??
  25. ???}??
  26. ??}??
  27. ?}??
  28. }??

?
效果如下:

?

選擇我們運行的程序:

監控運行狀態

轉載于:https://www.cnblogs.com/bill89/p/10483022.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/278223.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/278223.shtml
英文地址,請注明出處:http://en.pswp.cn/news/278223.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

一個在線編寫前端代碼的好玩的工具

https://codesandbox.io/ 可以編寫 Angular&#xff0c;React&#xff0c;Vue 等前端代碼。 可以實時編輯和 preview。 live 功能&#xff0c;可以多人協作編輯&#xff0c;不過是收費的功能。 可以增加依賴的包&#xff0c;比如編寫 React 時&#xff0c;可以安裝任意的第三…

MySQL數據庫基礎(五)——SQL查詢

MySQL數據庫基礎&#xff08;五&#xff09;——SQL查詢 一、單表查詢 1、查詢所有字段 在SELECT語句中使用星號“”通配符查詢所有字段在SELECT語句中指定所有字段select from TStudent; 2、查詢指定字段 查詢多個字段select Sname,sex,email from TStudent; 3、查詢指定記錄…

使用生成器創建新的迭代模式

一個函數中需要有一個 yield 語句即可將其轉換為一個生成器。 def frange(start, stop, increment):x startwhile x < stop:yield xx incrementfor i in frange(0, 4, 2):print(i) # 0 2 一個生成器函數主要特征是它只會回應在迭代中使用到的 next 操作 def cutdata(n):p…

前端異常捕獲與上報

在一般情況下我們代碼報錯啥的都會覺得 下圖 然后現在來說下經常用的異常 1.try catch 這個是比較常見的異常捕獲方式通常都是 使用try catch能夠很好的捕獲異常并對應進行相應處理&#xff0c;不至于讓頁面掛掉&#xff0c;但是其存在一些弊端&#xff0c;比如需要在捕獲異常的…

Codeforces 924D Contact ATC (看題解)

Contact ATC 我跑去列方程&#xff0c; 然后就gg了。。。 我們計每個飛機最早到達時間為L[ i ], 最晚到達時間為R[ i ]&#xff0c; 對于面對面飛行的一對飛機&#xff0c; 只要他們的時間有交集則必定滿足條件。 對于相同方向飛行的飛機&#xff0c; 只有其中一個的時間包含另…

基于ZXing Android實現生成二維碼圖片和相機掃描二維碼圖片即時解碼的功能

NextQRCode ZXing開源庫的精簡版 **基于ZXing Android實現生成二維碼圖片和相機掃描二維碼圖片即時解碼的功能原文博客 附源碼下載地址** 與原ZXingMini項目對比 NextQRCode做了重大架構修改&#xff0c;原ZXingMini項目與當前NextQRCode不兼容 dependencies {compile com.gith…

flask sqlalchemy 單表查詢

主要內容: 1 sqlalchemy: 一個python的ORM框架 2 使用sqlalchemy 的流程: 創建一個類 創建數據庫引擎 將所有的類序列化成數據表 進行增刪改查操作 # 1.創建一個 Class from sqlalchemy.ext.declarative import declarative_base Base declarative_base() # Base 是 ORM模型 基…

如何在Windows 7或Vista上安裝IIS

If you are a developer using ASP.NET, one of the first things you’ll want to install on Windows 7 or Vista is IIS (internet information server). Keep in mind that your version of Windows may not come with IIS. I’m using Windows 7 Ultimate edition. 如果您…

Dubbo的使用及原理淺析

https://www.cnblogs.com/wang-meng/p/5791598.html轉載于:https://www.cnblogs.com/h-wt/p/10490345.html

ThinkPHP3.2 實現阿里云OSS上傳文件

為什么80%的碼農都做不了架構師&#xff1f;>>> 0、配置文件Config&#xff0c;加入OSS配置選項&#xff0c;設置php.ini最大上傳大小&#xff08;自行解決&#xff0c;這里不做演示&#xff09; OSS > array(ACCESS_KEY_ID > **************, //從OSS獲得的…

ipad和iphone切圖_如何在iPhone,iPad和Mac上簽名PDF

ipad和iphone切圖Khamosh PathakKhamosh PathakDo you have documents to sign? You don’t need to worry about printing, scanning, or even downloading a third-party app. You can sign PDFs right on your iPhone, iPad, and Mac. 你有文件要簽名嗎&#xff1f; 您無需…

一個頁面上有大量的圖片(大型電商網站),加載很慢,你有哪些方法優化這些圖片的加載,給用戶更好的體驗。...

a. 圖片懶加載&#xff0c;滾動到相應位置才加載圖片。 b. 圖片預加載&#xff0c;如果為幻燈片、相冊等&#xff0c;將當前展示圖片的前一張和后一張優先下載。 c. 使用CSSsprite&#xff0c;SVGsprite&#xff0c;Iconfont、Base64等技術&#xff0c;如果圖片為css圖片的話。…

[function.require]: Failed opening required 杰奇cms

在配置杰奇cms移動端的時候&#xff0c;出現了[function.require]: Failed opening required 不要慌&#xff0c;百度一下即可解決。這個就是權限問題。由于移動端要請求pc端的文件&#xff0c;沒權限。加上一個iis_iusrs讀寫權限即可搞定&#xff01;轉載于:https://www.cnblo…

在Ubuntu服務器上打開第二個控制臺會話

Ubuntu Server has the native ability to run multiple console sessions from the server console prompt. If you are working on the actual console and are waiting for a long running command to finish, there’s no reason why you have to sit and wait… you can j…

Cloudstack系統配置(三)

系統配置 CloudStack提供一個基于web的UI&#xff0c;管理員和終端用戶能夠使用這個界面。用戶界面版本依賴于登陸時使用的憑證不同而不同。用戶界面是適用于大多數流行的瀏覽器包括IE7,IE8,IE9,Firefox Chrome等。URL是:(用你自己的管理控制服務器IP地址代替) 1http://<ma…

.NET Core 3.0-preview3 發布

.NET Core 3.0 Preview 3已經發布&#xff0c;框架和ASP.NET Core有許多有趣的更新。這是最重要的更新列表。 下載地址 :https://aka.ms/netcore3download 。.NET Core 3.0的更新&#xff1a;C&#xff03;中對索引和范圍的更多支持支持.NET Standard 2.1。以.NET Standard項目…

如何在Chrome工具欄中固定和取消固定擴展程序

Not all extensions are made equal. Some extensions, like Grammarly, work quietly in the background and don’t need an icon in the Chrome toolbar. Here’s how to pin and unpin extensions for a cleaner Chrome toolbar. 并非所有擴展名都相等。 某些擴展程序(例如…

vim編輯器快捷操作

1、查找 進入編輯器 按下 / 進行查找&#xff0c;回跳到第一個匹配的值&#xff0c;按下n查找下一個 N返回查看上一個 也可根據正則進行查找 2、替換 &#xff1a;s/a/b/g 當前行替換 &#xff1a;%s/a/b/g 全文替換 &#xff1a;5,10s/a/b/g 區域替換: .,2s/foo/bar/g 當…

react-navigation 跨 tabs 返回首頁

2019獨角獸企業重金招聘Python工程師標準>>> react-navigation 跨 tabs 返回首頁 import { NavigationActions } from react-navigation;const navigationAction NavigationActions.reset({ index: 0,actions: [ NavigationActions.navigate({ routeName: RootTab…

MySql:從任何主機授予根用戶登錄權限

Note that this is Not very secure, and should only be used for a local development box where you don’t feel like setting up individual permissions, but still need to connect from other machines. 請注意&#xff0c;這不是很安全&#xff0c;僅應用于您不想設置…