Java四種線程池的學習與總結

來源:互聯網
上載者:User

標籤:exe   最大並發數   second   timertask   ble   作用   timer   代碼   lex   

  在Java開發中,有時遇到多線程的開發時,直接使用Thread操作,對程式的效能和維護上都是一個問題,使用Java提供的線程池來操作可以很好的解決問題。

一、new Thread的弊端

執行一個非同步任務你還只是如下new Thread嗎?

new Thread(new Runnable(){    @Override    public void run(){          //TODO Auto-generatedmethod stub      }        }).start();               

那你就out太多了,new Thread的弊端如下:
1、每次new Thread建立對象效能差。

2、線程缺乏統一管理,可能無限制建立線程,相互之間競爭,有可能佔用過多系統資源導致死機或oom。

3、缺乏更多功能,如定時任務、定期執行、線程中斷。

相比new Thread,Java提供的四種線程池的好處在於:

1、重用存在的線程,減少對象建立、消亡的開銷,效能更佳。

2、可有效控制最大並發線程數,提高系統資源的使用率,同時避免過多資源競爭,避免堵塞。

3、提供定時執行、定期執行、單線程、並發數控制等功能。

二、Java 線程池

Java通過Executors提供四種線程池,分別為:

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

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

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

  newSingleThreadExecutor 建立一個單線程化的線程池,它只會用唯一的背景工作執行緒來執行任務,保證所有任務按照指定順序(FIFO,LIFO,優先順序)執行。

1、newCachedThreadPool:

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

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:

建立一個定長線程池,可控制線程最大並發數,超出的線程會在隊列中等待。範例程式碼如下:

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:

建立一個定長線程池,支援定時及週期性任務執行。順延強制範例程式碼如下:

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秒執行。

定期執行範例程式碼如下:

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,優先順序)執行。範例程式碼如下:

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

運行程式做稍微修改:

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();     }    }   }  }

效果如下:

選擇我們啟動並執行程式:

監控運行狀態

三、線程池的作用:

線程池作用就是限制系統中執行線程的數量。

根據系統的環境情況,可以自動或手動設定線程數量,達到啟動並執行最佳效果;少了浪費了系統資源,多了造成系統擁擠效率不高。用線程池控制線程數量,其他線程排 隊等候。一個任務執行完畢,再從隊列的中取最前面的任務開始執行。若隊列中沒有等待進程,線程池的這一資源處於等待。當一個新任務需要運行時,如果線程池 中有等待的背景工作執行緒,就可以開始運行了;否則進入等待隊列。

四、為什麼要用線程池:

1、減少了建立和銷毀線程的次數,每個背景工作執行緒都可以被重複利用,可執行多個任務。

2、可以根據系統的承受能力,調整線程池中工作線線程的數目,防止因為消耗過多的記憶體,而把伺服器累趴下(每個線程需要大約1MB記憶體,線程開的越多,消耗的記憶體也就越大,最後死機)。

Java裡麵線程池的頂級介面是Executor,但是嚴格意義上講Executor並不是一個線程池,而只是一個執行線程的工具。真正的線程池介面是ExecutorService。

比較重要的幾個類:

ExecutorService: 真正的線程池介面。

ScheduledExecutorService: 能和Timer/TimerTask類似,解決那些需要任務重複執行的問題。

ThreadPoolExecutor: ExecutorService的預設實現。

ScheduledThreadPoolExecutor: 繼承ThreadPoolExecutor的ScheduledExecutorService介面實現,週期性任務調度的類實現。

要配置一個線程池是比較複雜的,尤其是對於線程池的原理不是很清楚的情況下,很有可能配置的線程池不是較優的,因此在Executors類裡面提供了一些靜態工廠,產生一些常用的線程池。

1、newSingleThreadExecutor

建立一個單線程的線程池。這個線程池只有一個線程在工作,也就是相當於單線程串列執行所有任務。如果這個唯一的線程因為異常結束,那麼會有一個新的線程來替代它。此線程池保證所有任務的執行順序按照任務的提交順序執行。

2、newFixedThreadPool

建立固定大小的線程池。每次提交一個任務就建立一個線程,直到線程達到線程池的最大大小。線程池的大小一旦達到最大值就會保持不變,如果某個線程因為執行異常而結束,那麼線程池會補充一個新線程。

3、newCachedThreadPool

建立一個可快取的線程池。如果線程池的大小超過了處理任務所需要的線程,那麼就會回收部分空閑(60秒不執行任務)的線程,當任務數增加時,此線程池又可以智能的添加新線程來處理任務。此線程池不會對線程池大小做限制,線程池大小完全依賴於作業系統(或者說JVM)能夠建立的最大線程大小。

4、newScheduledThreadPool

建立一個大小固定的線程池。此線程池支援定時以及周期性執行任務的需求。

範例程式碼

一、固定大小的線程池,newFixedThreadPool:

package app.executors; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; /**  * Java線程:線程池  *   * @author xiho */ public class Test { public static void main(String[] args) { // 建立一個可重用固定線程數的線程池  ExecutorService pool = Executors.newFixedThreadPool(2); // 建立線程  Thread t1 = new MyThread(); Thread t2 = new MyThread(); Thread t3 = new MyThread(); Thread t4 = new MyThread(); Thread t5 = new MyThread(); // 將線程放入池中進行執行  pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); // 關閉線程池  pool.shutdown(); } } class MyThread extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName() + "正在執行。。。"); } }

輸出結果:

pool-1-thread-1正在執行。。。 pool-1-thread-3正在執行。。。pool-1-thread-4正在執行。。。 pool-1-thread-2正在執行。。。 pool-1-thread-5正在執行。。。

 改變ExecutorService pool = Executors.newFixedThreadPool(5)中的參數:ExecutorService pool = Executors.newFixedThreadPool(2),輸出結果是:

pool-1-thread-1正在執行。。。  pool-1-thread-1正在執行。。。  pool-1-thread-2正在執行。。。  pool-1-thread-1正在執行。。。  pool-1-thread-2正在執行。。。

從以上結果可以看出,newFixedThreadPool的參數指定了可以啟動並執行線程的最大數目,超過這個數目的線程加進去以後,不會運行。其次,加入線程池的線程屬於託管狀態,線程的運行不受加入順序的影響。

二、單任務線程池,newSingleThreadExecutor:

僅僅是把上述代碼中的ExecutorService pool = Executors.newFixedThreadPool(2)改為ExecutorService pool = Executors.newSingleThreadExecutor();
輸出結果:

pool-1-thread-1正在執行。。。  pool-1-thread-1正在執行。。。  pool-1-thread-1正在執行。。。  pool-1-thread-1正在執行。。。  pool-1-thread-1正在執行。。。 

可以看出,每次調用execute方法,其實最後都是調用了thread-1的run方法。

三、可變尺寸的線程池,newCachedThreadPool:

與上面的類似,只是改動下pool的建立方式:ExecutorService pool = Executors.newCachedThreadPool();
輸出結果:

pool-1-thread-1正在執行。。。  pool-1-thread-2正在執行。。。  pool-1-thread-4正在執行。。。  pool-1-thread-3正在執行。。。  pool-1-thread-5正在執行。。。

這種方式的特點是:可根據需要建立新線程的線程池,但是在以前構造的線程可用時將重用它們。

四、延遲串連池,newScheduledThreadPool:

public class TestScheduledThreadPoolExecutor {    public static void main(String[] args) {        ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);        exec.scheduleAtFixedRate(new Runnable() {//每隔一段時間就觸發異常                      @Override                      publicvoid run() {                           //throw new RuntimeException();                           System.out.println("================");                      }                  }, 1000, 5000, TimeUnit.MILLISECONDS);        exec.scheduleAtFixedRate(new Runnable() {//每隔一段時間列印系統時間,證明兩者是互不影響的                      @Override                      publicvoid run() {                           System.out.println(System.nanoTime());                      }                  }, 1000, 2000, TimeUnit.MILLISECONDS);    }}

輸出結果:

================ 8384644549516 8386643829034 8388643830710 ================ 8390643851383 8392643879319 8400643939383

 

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.