Java多線程-線程池架構

一)線程池架構

Java多線程中線程池架構圖如下:

 

二)Executor

Executor是一個接口,接口中只有一個execute()方法。

package java.util.concurrent;

public interface Executor {
    void execute(Runnable command);
}

Executor接口提供execute()方法來執行提交的Runnable任務對象。

Executor接口主要目的是提供一種將“任務提交”和“任務運行”分離開的機制,包括線程使用,調度等的Executor。

 

三)ExecutorService

ExecutorService是一個接口,繼承了Executor接口,提供了一些管理Executor的方法。

package java.util.concurrent;
import java.util.List;
import java.util.Collection;

public interface ExecutorService extends Executor {

    // 啓動有序關閉,其中先前提交的任務將被執行,但不會接受任何新任務。
    void shutdown();

    // 嘗試停止所有主動執行的任務,停止等待任務的處理,並返回正在等待執行的任務列表。
    List<Runnable> shutdownNow();

    // 如果此執行者已關閉,則返回 true。
    boolean isShutdown();

    // 如果所有任務在關閉後完成,則返回 true。 
    boolean isTerminated();

    // 阻止所有任務在關閉請求完成後執行,或發生超時,或當前線程中斷,以先到者爲準。
    boolean awaitTermination(long timeout, TimeUnit unit)
        throws InterruptedException;

    // 提交值返回任務以執行,並返回代表任務待處理結果的Future。
    <T> Future<T> submit(Callable<T> task);

    // 提交一個可運行的任務執行,並返回一個表示該任務的未來。
    <T> Future<T> submit(Runnable task, T result);

    // 提交一個可運行的任務執行,並返回一個表示該任務的未來。
    Future<?> submit(Runnable task);

    // 執行給定的任務,返回持有他們的狀態和結果的所有完成的期貨列表。
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
        throws InterruptedException;

    // 執行給定的任務,返回在所有完成或超時到期時持有其狀態和結果的期貨列表,以先發生者爲準。
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
                                  long timeout, TimeUnit unit)
        throws InterruptedException;

    // 執行給定的任務,返回一個成功完成的結果(即沒有拋出異常),如果有的話。
    <T> T invokeAny(Collection<? extends Callable<T>> tasks)
        throws InterruptedException, ExecutionException;

    // 執行給定的任務,返回一個已經成功完成的結果(即,不拋出異常),如果有的話在給定的超時之前過去。 
    <T> T invokeAny(Collection<? extends Callable<T>> tasks,
                    long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

 

四)AbstractExecutorService

AbstractExecutorService是一個抽象類,提供ExecutorService執行方法的默認實現。

該類實現submitinvokeAnyinvokeAll等方法,並使用RunnableFuture接口返回newTaskFor,其默認實現爲FutureTask類中提供。

 

五)ThreadPoolExecutor

ThreadPoolExecutor是線程池具體實現類,繼承了AbstractExecutorService抽象類。

該類提供了四種線程池創建方式

// 第一種:創建一個新的ThreadPoolExecutor與給定的初始參數和默認線程工廠和拒絕執行處理程序。
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
}

// 第二種:創建一個新的ThreadPoolExecutor與給定的初始參數和默認拒絕執行處理程序。 
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             threadFactory, defaultHandler);
}

// 第三種:創建一個新的 ThreadPoolExecutor與給定的初始參數和默認線程工廠。
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          RejectedExecutionHandler handler) {
    this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), handler);
}

// 第四種:創建一個新 ThreadPoolExecutor給定的初始參數。最終都是調用該方法。
public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler) {
    if (corePoolSize < 0 ||
        maximumPoolSize <= 0 ||
        maximumPoolSize < corePoolSize ||
        keepAliveTime < 0)
        throw new IllegalArgumentException();
    if (workQueue == null || threadFactory == null || handler == null)
        throw new NullPointerException();
    this.acc = System.getSecurityManager() == null ?
             null :
             AccessController.getContext();
    this.corePoolSize = corePoolSize;
    this.maximumPoolSize = maximumPoolSize;
    this.workQueue = workQueue;
    this.keepAliveTime = unit.toNanos(keepAliveTime);
    this.threadFactory = threadFactory;
    this.handler = handler;
}

 

該類提供了四種線程池拒絕策略

1)ThreadPoolExecutor.AbortPolicy:當任務添加到線程池中被拒絕時,它將拋出 RejectedExecutionException異常。

2)ThreadPoolExecutor.CallerRunsPolicy:當任務添加到線程池中被拒絕時,會在線程池當前正在運行的Thread線程池中處理被拒絕的任務。

3)ThreadPoolExecutor.DiscardOldestPolicy:當任務添加到線程池中被拒絕時,線程池會放棄等待隊列中最舊的未處理任務,然後將被拒絕的任務添加到等待隊列中。

4)ThreadPoolExecutor.DiscardPolicy:當任務添加到線程池中被拒絕時,線程池將丟棄被拒絕的任務。

 

六)ScheduledExecutorService

ScheduledExecutorService是一個接口,繼承了ExecutorService。它相當於提供了“延遲”或“定期執行”ExecutorService。

ScheduledExecutorService提供了一些函數方法來實現“延遲”或“定期執行”功能。

 

七)ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor實現了ScheduledExecutorService接口的相關函數方法,並繼承了ThreadPoolExecutor類。

ScheduledThreadPoolExecutor提供了具體實現“延遲”或“定期執行”功能代碼。相當於一個定時器。

 

八)Executors

Executors是一個靜態工廠類,類中都是static的函數方法。它通過靜態工廠方法返回ExecutorService、ScheduledExecutorService、ThreadFactory和Callable等類的對象。

一般情況,不需要通過ThreadPoolExecutor類中提供的四種線程創建方式來創建線程,可通過該類的靜態方法創建。

 

1)newCachedThreadPool():創建一個線程池,如果線程池中的線程數量過大,它可以有效的回收多餘的線程,如果線程數不足,那麼它可以創建新的線程。相當於一個緩存線程池。

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>(),
                                  threadFactory);
}

 

2)newFixedThreadPool():創建一個固定大小的線程池,如果線程超過固定大小,會進入阻塞狀態,是一個阻塞線程池。該方式1秒鐘最多支持1000個線程同時運行。

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>(),
                                  threadFactory);
}

 

3)newScheduledThreadPool():該線程池支持定時,以及週期性的任務執行,我們可以延遲任務的執行時間,也可以設置一個週期性的時間讓任務重複執行。

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}

public static ScheduledExecutorService newScheduledThreadPool(
        int corePoolSize, ThreadFactory threadFactory) {
    return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}

 

4)newSingleThreadExecutor():該方式會創建一個固定大小爲1的單線程,是一個單線程池,只會有一個線程運行,其它線程都會進入阻塞狀態,等待線程池的釋放和調用。

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}

public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>(),
                                threadFactory));
}

 

識別二維碼關注個人微信公衆號

本章完結,待續,歡迎轉載!
 
本文說明:該文章屬於原創,如需轉載,請標明文章轉載來源!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章