Java線程池應用

來源:互聯網
上載者:User

標籤:sleep   ace   調整   rri   not   簡單   on()   影響   service   

1.降低了建立和銷毀線程的次數。每一個背景工作執行緒都能夠被反覆利用。可運行多個任務。

2.能夠依據系統的承受能力,調整線程池中工作線線程的數目。防止由於消耗過多的記憶體。而把server累趴下(每一個線程須要大約1MB記憶體。線程開的越多,消耗的記憶體也就越大,最後死機)。

Java裡麵線程池的頂級介面是Executor,可是嚴格意義上講Executor並非一個線程池,而僅僅是一個運行線程的工具。真正的線程池介面是ExecutorService。

1. newSingleThreadExecutor

建立一個單線程的線程池。這個線程池僅僅有一個線程在工作,也就是相當於單線程串列運行全部任務。假設這個唯一的線程由於異常結束,那麼會有一個新的線程來替代它。此線程池保證全部任務的運行順序依照任務的提交順序運行。

2.newFixedThreadPool

建立固定大小的線程池。

每次提交一個任務就建立一個線程,直到線程達到線程池的最大大小。線程池的大小一旦達到最大值就會保持不變,假設某個線程由於運行異常而結束。那麼線程池會補充一個新線程。

3. newCachedThreadPool

建立一個可快取的線程池。假設線程池的大小超過了處理任務所須要的線程,

那麼就會回收部分空暇(60秒不運行任務)的線程,當任務數添加時,此線程池又可以智能的加入新線程來處理任務。此線程池不會對線程池大小做限制。線程池大小全然依賴於作業系統(或者說JVM)可以建立的最大線程大小。

4.newScheduledThreadPool

建立一個大小無限的線程池。

此線程池支援定時以及周期性運行任務的需求


以下我用2個執行個體來說明一下 ,線程池的簡單有用

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;public class ThreadPool {     public static void main(String[] args) {     //ExecutorService ThreadPool =  Executors.newFixedThreadPool(3);     //ExecutorService ThreadPool = Executors.newCachedThreadPool();      ExecutorService ThreadPool = Executors.newSingleThreadExecutor();     for(int i=0;i<=4;i++){     final int task = i;         ThreadPool.execute(new Runnable() {@Overridepublic void run() {                for(int j=0;j<=10;j++){                try {Thread.sleep(20);} catch (InterruptedException e) {e.printStackTrace();}                System.out.println(Thread.currentThread().getName() + " is loopping of " + j + " for task of " + task);                }}});       }     //ThreadPool.shutdownNow();     Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() {@Overridepublic void run() {System.out.println("boombing!!");}}, 5, 2, TimeUnit.SECONDS);}}

publicclass TestScheduledThreadPoolExecutor {    publicstaticvoid 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);    }}


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.