Java四種線程池的使用

來源:互聯網
上載者:User

標籤:

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. }

package test;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ThreadPoolExecutorTest { public static void main(String[] args) {  ExecutorService cachedThreadPool = Executors.newCachedThreadPool();  for (int i = 0; i < 10; i++) {   final int index = i;   try {    Thread.sleep(index * 1000);   } catch (InterruptedException e) {    e.printStackTrace();   }   cachedThreadPool.execute(new Runnable() {    public void run() {     System.out.println(index);    }   });  } }}

線程池為無限大,當執行第二個任務時第一個任務已經完成,會複用執行第一個任務的線程,而不用每次建立線程。

(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. }

package test;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ThreadPoolExecutorTest { public static void main(String[] args) {  ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);  for (int i = 0; i < 10; i++) {   final int index = i;   fixedThreadPool.execute(new Runnable() {    public void run() {     try {      System.out.println(index);      Thread.sleep(2000);     } catch (InterruptedException e) {      e.printStackTrace();     }    }   });  } }}


因為線程池大小為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. }

package test;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class ThreadPoolExecutorTest { public static void main(String[] args) {  ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);  scheduledThreadPool.schedule(new Runnable() {   public void run() {    System.out.println("delay 3 seconds");   }  }, 3, TimeUnit.SECONDS); }}


表示延遲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. }

package test;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;public class ThreadPoolExecutorTest { public static void main(String[] args) {  ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);  scheduledThreadPool.scheduleAtFixedRate(new Runnable() {   public void run() {    System.out.println("delay 1 seconds, and excute every 3 seconds");   }  }, 1, 3, TimeUnit.SECONDS); }}


表示延遲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. }

package test;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ThreadPoolExecutorTest { public static void main(String[] args) {  ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();  for (int i = 0; i < 10; i++) {   final int index = i;   singleThreadExecutor.execute(new Runnable() {    public void run() {     try {      System.out.println(index);      Thread.sleep(2000);     } catch (InterruptedException e) {      e.printStackTrace();     }    }   });  } }}


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

你可以使用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. }

package test;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ThreadPoolExecutorTest { public static void main(String[] args) {  ExecutorService singleThreadExecutor = Executors.newCachedThreadPool();  for (int i = 0; i < 100; i++) {   final int index = i;   singleThreadExecutor.execute(new Runnable() {    public void run() {     try {      while(true) {       System.out.println(index);       Thread.sleep(10 * 1000);      }     } catch (InterruptedException e) {      e.printStackTrace();     }    }   });   try {    Thread.sleep(500);   } catch (InterruptedException e) {    e.printStackTrace();   }  } }}

Java四種線程池的使用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.