天天看點

java 四種 線程池

java通過executors提供四種線程池,分别為:

newcachedthreadpool建立一個可緩存線程池,如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則建立線程。

newfixedthreadpool 建立一個定長線程池,可控制線程最大并發數,超出的線程會在隊列中等待。

newscheduledthreadpool 建立一個定長線程池,支援定時及周期性任務執行。

newsinglethreadexecutor 建立一個單線程化的線程池,它隻會用唯一的工作線程來執行任務,保證所有任務按照指定順序(fifo, lifo, 優先級)執行。

(1)

newcachedthreadpool

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

java 四種 線程池

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 四種 線程池

  executorservice fixedthreadpool = executors.newfixedthreadpool(3);  

   fixedthreadpool.execute(new runnable() {  

     try {  

      system.out.println(index);  

      thread.sleep(2000);  

     } catch (interruptedexception e) {  

      e.printstacktrace();  

     }  

因為線程池大小為3,每個任務輸出index後sleep 2秒,是以每兩秒列印3個數字。

定長線程池的大小最好根據系統資源進行設定。如runtime.getruntime().availableprocessors()

(3)  newscheduledthreadpool

建立一個定長線程池,支援定時及周期性任務執行。延遲執行示例代碼如下:

java 四種 線程池

import java.util.concurrent.scheduledexecutorservice;  

import java.util.concurrent.timeunit;  

  scheduledexecutorservice scheduledthreadpool = executors.newscheduledthreadpool(5);  

  scheduledthreadpool.schedule(new runnable() {  

   public void run() {  

    system.out.println("delay 3 seconds");  

  }, 3, timeunit.seconds);  

表示延遲3秒執行。

定期執行示例代碼如下:

java 四種 線程池

  scheduledthreadpool.scheduleatfixedrate(new runnable() {  

    system.out.println("delay 1 seconds, and excute every 3 seconds");  

  }, 1, 3, timeunit.seconds);  

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

(4) newsinglethreadexecutor

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

java 四種 線程池

  executorservice singlethreadexecutor = executors.newsinglethreadexecutor();  

   singlethreadexecutor.execute(new runnable() {  

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

你可以使用jdk自帶的監控工具來監控我們建立的線程數量,運作一個不終止的線程,建立指定量的線程,來觀察:

工具目錄:c:\program files\java\jdk1.6.0_06\bin\jconsole.exe

運作程式做稍微修改:

java 四種 線程池

  executorservice singlethreadexecutor = executors.newcachedthreadpool();  

  for (int i = 0; i < 100; i++) {  

      while(true) {  

       system.out.println(index);  

       thread.sleep(10 * 1000);  

      }  

    thread.sleep(500);  

效果如下:

java 四種 線程池

選擇我們運作的程式:

java 四種 線程池

監控運作狀态

轉載自:http://cuisuqiang.iteye.com/blog/2019372