Java線程池類ThreadPoolExecutor、ScheduledThreadPoolExecutor及Executors工廠類

來源:互聯網
上載者:User

標籤:end   system   沒有   article   接收   隊列   閱讀   max   UI   

引用:http://blog.csdn.net/suifeng3051/article/details/49444177

Java中的線程池類有兩個,分別是:ThreadPoolExecutor和ScheduledThreadPoolExecutor,這兩個類都繼承自ExecutorService。利用這兩個類,可以建立各種不同的Java線程池,為了方便我們建立線程池,Java API提供了Executors工廠類來協助我們建立各種各樣的線程池。下面我們分別介紹一下這三個類。

Java線程池ExecutorService繼承樹:

一、ThreadPoolExecutor

ThreadPoolExecutor是ExecutorService的一個實作類別,也是java中最常用的線程池類。ThreadPoolExecutor內部維持了一個線程池,可以執行給定的任務,下面是關於它的具體使用方法。

1.1 ThreadPoolExecutor構造方法及其作用

ThreadPoolExecutor源碼中的構造方法:

- corePoolSize:線程池維護線程的最少數量- maximumPoolSize:線程池維護線程的最大數量- keepAliveTime: 線程池維護線程所允許的空閑時間- unit: 線程池維護線程所允許的空閑時間的單位- workQueue: 線程池所使用的緩衝隊列- handler: 線程池對拒絕任務的處理策略
1.2 線程數量控制

ThreadPoolExecutor線程池中的線程數量是可變的,其變化範圍取決於下面兩個變數:

1. corePoolSize:線程池維護線程的最少數量2. maximumPoolSize:線程池維護線程的最大數量

具體線程的分配方式是,當一個任務被添加到線程池:

1. 如果此時線程池中的數量小於corePoolSize,即使線程池中的線程都處於空閑狀態,也要建立新的線程來處理被添加的任務。2. 如果此時線程池中的數量等於 corePoolSize,但是緩衝隊列 workQueue未滿,那麼任務被放入緩衝隊列。3. 如果此時線程池中的數量大於corePoolSize,緩衝隊列workQueue滿,並且線程池中的數量小於maximumPoolSize,建新的線程來處理被添加的任務。4. 如果此時線程池中的數量大於corePoolSize,緩衝隊列workQueue滿,並且線程池中的數量等於maximumPoolSize,那麼通過 handler所指定的策略來處理此任務。也就是:處理任務的優先順序為:核心線程corePoolSize、任務隊列workQueue、最大線程maximumPoolSize,如果三者都滿了,使用handler處理被拒絕的任務。5. 當線程池中的線程數量大於 corePoolSize時,如果某線程空閑時間超過keepAliveTime,線程將被終止。

這樣,線程池可以動態調整池中的線程數。除了corePoolSize、maximumPoolSize兩個變數外,ThreadPoolExecutor構造方法還有幾個參數:

- keepAliveTime: 線程池維護線程所允許的空閑時間- unit: 線程池維護線程所允許的空閑時間的單位- workQueue: 線程池所使用的緩衝隊列- handler: 線程池對拒絕任務的處理策略
1.2 unit

unit 可選的參數為java.util.concurrent.TimeUnit中的幾個靜態屬性:

- NANOSECONDS- MICROSECONDS- MILLISECONDS- SECONDS
1.3 workQueue

workQueue是一個BlockingQueue,預設是LinkedBlockingQueue<Runnable>

1.4 handler

handler 是線程池拒絕處理任務的方式,主要有四種類型:

  1. ThreadPoolExecutor.AbortPolicy()(系統預設):拋出java.util.concurrent.RejectedExecutionException異常
  2. ThreadPoolExecutor.CallerRunsPolicy():當拋出RejectedExecutionException異常時,會調用rejectedExecution方法
  3. ThreadPoolExecutor.DiscardOldestPolicy():拋棄舊的任務
  4. ThreadPoolExecutor.DiscardPolicy():拋棄當前的任務
1.5 建立一個ThreadPoolExecutor
int  corePoolSize  =    5;int  maxPoolSize   =   10;long keepAliveTime = 5000;ExecutorService threadPoolExecutor =    new ThreadPoolExecutor(            corePoolSize,            maxPoolSize,            keepAliveTime,            TimeUnit.MILLISECONDS,                new LinkedBlockingQueue<Runnable>()            );
二、ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor是ExecutorService的另一個實作類別,從上面Java線程池ExecutorService繼承樹這幅圖可以看出,ScheduledThreadPoolExecutor直接繼承自ScheduledExecutorService,ScheduledThreadPoolExecutor 類的功能也主要體現在ScheduledExecutorService 介面上,而所以在介紹ScheduledThreadPoolExecutor之前先介紹一下ScheduledExecutorService介面。

2.1 ScheduledExecutorService介面介紹

java.util.concurrent.ScheduledExecutorService介面繼承了ExecutorService,它的最主要的功能就是可以對其中的任務進行調度,比如順延強制、定時執行等等。

ScheduledExecutorService介面定義:

public interface ScheduledExecutorService extends ExecutorService {    public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit);    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,long initialDelay, long period, TimeUnit unit);    public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,long initialDelay, long delay,TimeUnit unit);}

從上面介面定義我們知道,提供了四個方法,下面我們就分別介紹:

1. schedule (Runnable task, long delay, TimeUnit timeunit)2. schedule (Callable task, long delay, TimeUnit timeunit)3. scheduleAtFixedRate (Runnable, long initialDelay, long period, TimeUnit timeunit)4. scheduleWithFixedDelay (Runnable, long initialDelay, long period, TimeUnit timeunit)
2.1.1 schedule (Runnable task, long delay, TimeUnit timeunit)

這個方法的意思是在指定延遲之後運行task。這個方法有個問題,就是沒有辦法獲知task的執行結果。如果我們想獲得task的執行結果,我們可以傳入一個Callable的執行個體(後面會介紹)。

ScheduledExecutorService scheduledExecutorService =    Executors.newScheduledThreadPool(5);ScheduledFuture scheduledFuture =scheduledExecutorService.schedule(new Callable() {    public Object call() throws Exception {        System.out.println("Executed!");        return "Called!";    }},5,TimeUnit.SECONDS);System.out.println("result = " + scheduledFuture.get());scheduledExecutorService.shutdown();
2.1.2 schedule (Callable task, long delay, TimeUnit timeunit)

這個方法與schedule (Runnable task)類似,也是在指定延遲之後運行task,不過它接收的是一個Callable執行個體,此方法會返回一個ScheduleFuture對象,通過ScheduleFuture我們可以取消一個未執行的task,也可以獲得這個task的執行結果。

ScheduledExecutorService scheduledExecutorService =    Executors.newScheduledThreadPool(5);ScheduledFuture scheduledFuture =scheduledExecutorService.schedule(new Callable() {    public Object call() throws Exception {        System.out.println("Executed!");        return "Called!";    }},5,TimeUnit.SECONDS);System.out.println("result = " + scheduledFuture.get());scheduledExecutorService.shutdown();
2.1.3 scheduleAtFixedRate (Runnable, long initialDelay, long period, TimeUnit timeunit)

這個方法的作用是周期性的調度task執行。task第一次執行的延遲根據initialDelay參數確定,以後每一次執行都間隔period時間長度。

如果task的執行時間大於定義的period,那麼下一個線程將在當前線程完成之後再執行。整個調度保證不會出現一個以上任務同時執行。

2.1.4 scheduleWithFixedDelay (Runnable, long initialDelay, long period, TimeUnit timeunit)

scheduleWithFixedDelay的參數和scheduleAtFixedRate參數完全一致,它們的不同之處在於對period調度周期的解釋。

在scheduleAtFixedRate中,period指的兩個任務開始執行的時間間隔,也就是當前任務的開始執行時間和下個任務的開始執行時間之間的間隔。

而在scheduleWithFixedDelay中,period指的當前任務的結束執行時間到下個任務的開始執行時間。

2.1.5 ScheduledExecutorService的關閉

和ExecutorService類似, 我們在使用完ScheduledExecutorService時需要關閉它。如果不關閉的話,JVM會一直運行直,即使所有線程已經關閉了。

關閉ScheduledExecutorService可以使用其繼承自ExecutorService介面的shutdown()和shutdownNow()方法,兩者的區別請參考【Java線程池 ExecutorService】。

2.2 ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor繼承自ThreadPoolExecutor,構造參數很簡單,只有3個:

1. int corePoolSize:線程池維護線程的最少數量2. ThreadFactory threadFactory:線程工程類,線程池用它來製造線程3. RejectedExecutionHandler handler:線程池對拒絕任務的處理策略

具體使用方法請參考ThreadPoolExecutor或者使用Executors。

三、Executors

建立一個什麼樣的ExecutorService的執行個體(即線程池)需要我們的具體應用情境而定,不過Java給我們提供了一個Executors工廠類,它可以協助我們很方便的建立各種類型ExecutorService線程池,Executors一共可以建立下面這四類線程池:

1. newCachedThreadPool 建立一個可緩衝線程池,如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則建立線程。2. newFixedThreadPool 建立一個定長線程池,可控制線程最大並發數,超出的線程會在隊列中等待。3. newScheduledThreadPool 建立一個定長線程池,支援定時及週期性任務執行。4. newSingleThreadExecutor 建立一個單線程化的線程池,它只會用唯一的背景工作執行緒來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先順序)執行。

 

備忘:Executors只是一個工廠類,它所有的方法返回的都是ThreadPoolExecutor、ScheduledThreadPoolExecutor這兩個類的執行個體。

閱讀完本文強烈建議閱讀一下【Java線程池 ExecutorService】。

Java線程池類ThreadPoolExecutor、ScheduledThreadPoolExecutor及Executors工廠類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.