淺聊JAVA 線程池的一般用法

來源:互聯網
上載者:User

標籤:round   time   exce   http   之間   block   thread   ges   for   

一、為什麼要用線程池

  1)、降低資源消耗,通過重複利用已建立的線程降低線程的建立和銷毀造成的消耗。

  2)、提高響應速度,當任務到達時,任務可以不需要等到線程建立就能立即執行。

  3)、提高線程的可管理性,線程是稀缺資源,如果無限制的建立,不僅會消耗系統資源,還會降低系統的穩定性,使用線程池可以進行統一的分配,調優和監控。

二、注意

  1)、需要對線程池原理了如指掌。

三、線程的常見用法

  1)、New Thread。

  2)、Thread Pool。

 

四、New Thread 常見用法

    new  thread(new Runnable(){

      @Override

      public void run(){

      //TODO anything you need

      }  

    })

         作為一個嚴謹的dev來說,new thread 一般是禁止在代碼中使用的,new thread 存在許多弊端,例如:

    a)、每次new thread 都建立一個線程,效能差。

    b)、線程缺乏統一管理,高並發時線程會無限制的建立,相互之間競爭資源,最終會因為佔用過大資源導致死機或oom。

    c)、缺乏更多擴充功能,如定時執行、定期執行、線程中斷。

 

五、JAVA 線程池

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

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

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

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

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

  a)、newCachedThreadPool

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

    執行個體代碼:

    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() {

        @Override
        public void run() {
        System.out.println(index);
        }
      });
    }

             但是看到上面代碼,大家會不會有個疑問,上面代碼反覆執行,不是會建立多個線程池嗎?

    是不是應該把線程池做成單例的?

    public class CachedThreadPoolProxy  {

      public static final ExecutorService  cachedThreadPool   = Executors.newCachedThreadPool();

    }

           下面我們來做個Test:

  @Test    public void test() throws InterruptedException {                for (int i = 1; i < 100; i++) {            final int index = i;            ExecutorService executor = Executors.newCachedThreadPool();//ThreadPoolProxy.cachedThreadPool;                        executor.execute(new Runnable() {                public void run() {                    System.out.println(String.format("當前線程:%d", index));                }            });            int activeCount = ((ThreadPoolExecutor) executor).getActiveCount();            System.out.println(String.format("當前線程數量:%d", activeCount));            System.out.println(String.format("當前線程hashCode:%s", executor.hashCode()));        }    }

 

運行結果:

結論:

1、線程池會被多次建立,我們需要把線程池寫成單例。

2、線程的執行是無序的。

3、會自動回收空閑線程,無空閑線程時,線程會被不斷建立。

 

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

    範例程式碼如下:

@Testpublic void test2() throws InterruptedException {for (int i = 1; i < 100; i++) {final int index = i;ExecutorService executor = ThreadPoolProxy.fixedThreadPool;executor.execute(new Runnable() {public void run() {System.out.println(String.format("當前線程:%d", index));}});int activeCount = ((ThreadPoolExecutor) executor).getActiveCount();int blockCount = ((ThreadPoolExecutor) executor).getQueue().size();System.out.println(String.format("當前線程數量:%d", activeCount));System.out.println(String.format("當前線程hashCode:%s", executor.hashCode()));System.out.println(String.format("當前隊列的任務數:%s", blockCount));}}

  結果樣本:

     

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

  順延強制範例程式碼如下:

@Testpublic void test3() throws InterruptedException {ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);// ThreadPoolProxy.scheduledThreadPool;executor.scheduleAtFixedRate(new Runnable() {public void run() {System.out.println(new Date().getTime());System.out.println("正在執行。。。。");}}, 1, 3, TimeUnit.MILLISECONDS);}

  執行上述代碼時,發現程式並沒有輸出,心裡當時充滿了疑慮,幾經測試,發現是因為主線程終止了,schedual 也會停止運行。

@Testpublic void test3() throws InterruptedException {ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);// ThreadPoolProxy.scheduledThreadPool;executor.scheduleAtFixedRate(new Runnable() {public void run() {System.out.println(new Date().getTime());System.out.println("正在執行...");}}, 1, 3, TimeUnit.MILLISECONDS);Thread.sleep(100000);}

  

 

  d)、newSingleThreadExecutor

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

  

@Testpublic void test4() throws InterruptedException {ExecutorService executor = ThreadPoolProxy.singleThreadExecutor;for (int i = 0; i < 10000; i++) {final int index = i;executor.execute(new Runnable() {public void run() {System.out.println(index);}});}}

  

  可以看出結果依次輸出

     

PS: 源碼

public class ThreadPoolProxy {public static final ExecutorService cachedThreadPool = Executors.newCachedThreadPool();public static final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);public static final ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);public static final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();}

  

  

  

      

 

淺聊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.