概要
前面分別介紹了"Java多線程基礎"、"JUC原子類"和"JUC鎖"。本章介紹JUC的最后一部分的內容——線程池。內容包括:
線程池架構圖
線程池示例
轉載請注明出處:http://www.cnblogs.com/skywang12345/p/3509903.html
線程池架構圖
線程池的架構圖如下:
1. Executor
它是"執行者"接口,它是來執行任務的。准確的說,Executor提供了execute()接口來執行已提交的 Runnable 任務的對象。Executor存在的目的是提供一種將"任務提交"與"任務如何運行"分離開來的機制。
它只包含一個函數接口:
void execute(Runnable command)
2. ExecutorService
ExecutorService繼承於Executor。它是"執行者服務"接口,它是為"執行者接口Executor"服務而存在的;准確的話,ExecutorService提供了"將任務提交給執行者的接口(submit方法)","讓執行者執行任務(invokeAll, invokeAny方法)"的接口等等。
ExecutorService的函數列表

1 // 請求關閉、發生超時或者當前線程中斷,無論哪一個首先發生之后,都將導致阻塞,直到所有任務完成執行。 2 boolean awaitTermination(long timeout, TimeUnit unit) 3 // 執行給定的任務,當所有任務完成時,返回保持任務狀態和結果的 Future 列表。 4 <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) 5 // 執行給定的任務,當所有任務完成或超時期滿時(無論哪個首先發生),返回保持任務狀態和結果的 Future 列表。 6 <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) 7 // 執行給定的任務,如果某個任務已成功完成(也就是未拋出異常),則返回其結果。 8 <T> T invokeAny(Collection<? extends Callable<T>> tasks) 9 // 執行給定的任務,如果在給定的超時期滿前某個任務已成功完成(也就是未拋出異常),則返回其結果。 10 <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) 11 // 如果此執行程序已關閉,則返回 true。 12 boolean isShutdown() 13 // 如果關閉后所有任務都已完成,則返回 true。 14 boolean isTerminated() 15 // 啟動一次順序關閉,執行以前提交的任務,但不接受新任務。 16 void shutdown() 17 // 試圖停止所有正在執行的活動任務,暫停處理正在等待的任務,並返回等待執行的任務列表。 18 List<Runnable> shutdownNow() 19 // 提交一個返回值的任務用於執行,返回一個表示任務的未決結果的 Future。 20 <T> Future<T> submit(Callable<T> task) 21 // 提交一個 Runnable 任務用於執行,並返回一個表示該任務的 Future。 22 Future<?> submit(Runnable task) 23 // 提交一個 Runnable 任務用於執行,並返回一個表示該任務的 Future。 24 <T> Future<T> submit(Runnable task, T result)
3. AbstractExecutorService
AbstractExecutorService是一個抽象類,它實現了ExecutorService接口。
AbstractExecutorService存在的目的是為ExecutorService中的函數接口提供了默認實現。
AbstractExecutorService函數列表
由於它的函數列表和ExecutorService一樣,這里就不再重復列舉了。
4. ThreadPoolExecutor
ThreadPoolExecutor就是大名鼎鼎的"線程池"。它繼承於AbstractExecutorService抽象類。
ThreadPoolExecutor函數列表

1 // 用給定的初始參數和默認的線程工廠及被拒絕的執行處理程序創建新的 ThreadPoolExecutor。 2 ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) 3 // 用給定的初始參數和默認的線程工廠創建新的 ThreadPoolExecutor。 4 ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) 5 // 用給定的初始參數和默認被拒絕的執行處理程序創建新的 ThreadPoolExecutor。 6 ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) 7 // 用給定的初始參數創建新的 ThreadPoolExecutor。 8 ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) 9 10 // 基於完成執行給定 Runnable 所調用的方法。 11 protected void afterExecute(Runnable r, Throwable t) 12 // 如果在保持活動時間內沒有任務到達,新任務到達時正在替換(如果需要),則設置控制核心線程是超時還是終止的策略。 13 void allowCoreThreadTimeOut(boolean value) 14 // 如果此池允許核心線程超時和終止,如果在 keepAlive 時間內沒有任務到達,新任務到達時正在替換(如果需要),則返回 true。 15 boolean allowsCoreThreadTimeOut() 16 // 請求關閉、發生超時或者當前線程中斷,無論哪一個首先發生之后,都將導致阻塞,直到所有任務完成執行。 17 boolean awaitTermination(long timeout, TimeUnit unit) 18 // 在執行給定線程中的給定 Runnable 之前調用的方法。 19 protected void beforeExecute(Thread t, Runnable r) 20 // 在將來某個時間執行給定任務。 21 void execute(Runnable command) 22 // 當不再引用此執行程序時,調用 shutdown。 23 protected void finalize() 24 // 返回主動執行任務的近似線程數。 25 int getActiveCount() 26 // 返回已完成執行的近似任務總數。 27 long getCompletedTaskCount() 28 // 返回核心線程數。 29 int getCorePoolSize() 30 // 返回線程保持活動的時間,該時間就是超過核心池大小的線程可以在終止前保持空閑的時間值。 31 long getKeepAliveTime(TimeUnit unit) 32 // 返回曾經同時位於池中的最大線程數。 33 int getLargestPoolSize() 34 // 返回允許的最大線程數。 35 int getMaximumPoolSize() 36 // 返回池中的當前線程數。 37 int getPoolSize() 38 // 返回此執行程序使用的任務隊列。 39 BlockingQueue<Runnable> getQueue() 40 // 返回用於未執行任務的當前處理程序。 41 RejectedExecutionHandler getRejectedExecutionHandler() 42 // 返回曾計划執行的近似任務總數。 43 long getTaskCount() 44 // 返回用於創建新線程的線程工廠。 45 ThreadFactory getThreadFactory() 46 // 如果此執行程序已關閉,則返回 true。 47 boolean isShutdown() 48 // 如果關閉后所有任務都已完成,則返回 true。 49 boolean isTerminated() 50 // 如果此執行程序處於在 shutdown 或 shutdownNow 之后正在終止但尚未完全終止的過程中,則返回 true。 51 boolean isTerminating() 52 // 啟動所有核心線程,使其處於等待工作的空閑狀態。 53 int prestartAllCoreThreads() 54 // 啟動核心線程,使其處於等待工作的空閑狀態。 55 boolean prestartCoreThread() 56 // 嘗試從工作隊列移除所有已取消的 Future 任務。 57 void purge() 58 // 從執行程序的內部隊列中移除此任務(如果存在),從而如果尚未開始,則其不再運行。 59 boolean remove(Runnable task) 60 // 設置核心線程數。 61 void setCorePoolSize(int corePoolSize) 62 // 設置線程在終止前可以保持空閑的時間限制。 63 void setKeepAliveTime(long time, TimeUnit unit) 64 // 設置允許的最大線程數。 65 void setMaximumPoolSize(int maximumPoolSize) 66 // 設置用於未執行任務的新處理程序。 67 void setRejectedExecutionHandler(RejectedExecutionHandler handler) 68 // 設置用於創建新線程的線程工廠。 69 void setThreadFactory(ThreadFactory threadFactory) 70 // 按過去執行已提交任務的順序發起一個有序的關閉,但是不接受新任務。 71 void shutdown() 72 // 嘗試停止所有的活動執行任務、暫停等待任務的處理,並返回等待執行的任務列表。 73 List<Runnable> shutdownNow() 74 // 當 Executor 已經終止時調用的方法。 75 protected void terminated()
5. ScheduledExecutorService
ScheduledExecutorService是一個接口,它繼承於於ExecutorService。它相當於提供了"延時"和"周期執行"功能的ExecutorService。
ScheduledExecutorService提供了相應的函數接口,可以安排任務在給定的延遲后執行,也可以讓任務周期的執行。
ScheduledExecutorService函數列表

1 // 創建並執行在給定延遲后啟用的 ScheduledFuture。 2 <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) 3 // 創建並執行在給定延遲后啟用的一次性操作。 4 ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) 5 // 創建並執行一個在給定初始延遲后首次啟用的定期操作,后續操作具有給定的周期;也就是將在 initialDelay 后開始執行,然后在 initialDelay+period 后執行,接着在 initialDelay + 2 * period 后執行,依此類推。 6 ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) 7 // 創建並執行一個在給定初始延遲后首次啟用的定期操作,隨后,在每一次執行終止和下一次執行開始之間都存在給定的延遲。 8 ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit)
6. ScheduledThreadPoolExecutor
ScheduledThreadPoolExecutor繼承於ThreadPoolExecutor,並且實現了ScheduledExecutorService接口。它相當於提供了"延時"和"周期執行"功能的ScheduledExecutorService。
ScheduledThreadPoolExecutor類似於Timer,但是在高並發程序中,ScheduledThreadPoolExecutor的性能要優於Timer。
ScheduledThreadPoolExecutor函數列表

1 // 使用給定核心池大小創建一個新 ScheduledThreadPoolExecutor。 2 ScheduledThreadPoolExecutor(int corePoolSize) 3 // 使用給定初始參數創建一個新 ScheduledThreadPoolExecutor。 4 ScheduledThreadPoolExecutor(int corePoolSize, RejectedExecutionHandler handler) 5 // 使用給定的初始參數創建一個新 ScheduledThreadPoolExecutor。 6 ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory) 7 // 使用給定初始參數創建一個新 ScheduledThreadPoolExecutor。 8 ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler) 9 10 // 修改或替換用於執行 callable 的任務。 11 protected <V> RunnableScheduledFuture<V> decorateTask(Callable<V> callable, RunnableScheduledFuture<V> task) 12 // 修改或替換用於執行 runnable 的任務。 13 protected <V> RunnableScheduledFuture<V> decorateTask(Runnable runnable, RunnableScheduledFuture<V> task) 14 // 使用所要求的零延遲執行命令。 15 void execute(Runnable command) 16 // 獲取有關在此執行程序已 shutdown 的情況下、是否繼續執行現有定期任務的策略。 17 boolean getContinueExistingPeriodicTasksAfterShutdownPolicy() 18 // 獲取有關在此執行程序已 shutdown 的情況下是否繼續執行現有延遲任務的策略。 19 boolean getExecuteExistingDelayedTasksAfterShutdownPolicy() 20 // 返回此執行程序使用的任務隊列。 21 BlockingQueue<Runnable> getQueue() 22 // 從執行程序的內部隊列中移除此任務(如果存在),從而如果尚未開始,則其不再運行。 23 boolean remove(Runnable task) 24 // 創建並執行在給定延遲后啟用的 ScheduledFuture。 25 <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) 26 // 創建並執行在給定延遲后啟用的一次性操作。 27 ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) 28 // 創建並執行一個在給定初始延遲后首次啟用的定期操作,后續操作具有給定的周期;也就是將在 initialDelay 后開始執行,然后在 initialDelay+period 后執行,接着在 initialDelay + 2 * period 后執行,依此類推。 29 ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) 30 // 創建並執行一個在給定初始延遲后首次啟用的定期操作,隨后,在每一次執行終止和下一次執行開始之間都存在給定的延遲。 31 ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) 32 // 設置有關在此執行程序已 shutdown 的情況下是否繼續執行現有定期任務的策略。 33 void setContinueExistingPeriodicTasksAfterShutdownPolicy(boolean value) 34 // 設置有關在此執行程序已 shutdown 的情況下是否繼續執行現有延遲任務的策略。 35 void setExecuteExistingDelayedTasksAfterShutdownPolicy(boolean value) 36 // 在以前已提交任務的執行中發起一個有序的關閉,但是不接受新任務。 37 void shutdown() 38 // 嘗試停止所有正在執行的任務、暫停等待任務的處理,並返回等待執行的任務列表。 39 List<Runnable> shutdownNow() 40 // 提交一個返回值的任務用於執行,返回一個表示任務的未決結果的 Future。 41 <T> Future<T> submit(Callable<T> task) 42 // 提交一個 Runnable 任務用於執行,並返回一個表示該任務的 Future。 43 Future<?> submit(Runnable task) 44 // 提交一個 Runnable 任務用於執行,並返回一個表示該任務的 Future。 45 <T> Future<T> submit(Runnable task, T result)
7. Executors
Executors是個靜態工廠類。它通過靜態工廠方法返回ExecutorService、ScheduledExecutorService、ThreadFactory 和 Callable 等類的對象。
Executors函數列表

1 // 返回 Callable 對象,調用它時可運行給定特權的操作並返回其結果。 2 static Callable<Object> callable(PrivilegedAction<?> action) 3 // 返回 Callable 對象,調用它時可運行給定特權的異常操作並返回其結果。 4 static Callable<Object> callable(PrivilegedExceptionAction<?> action) 5 // 返回 Callable 對象,調用它時可運行給定的任務並返回 null。 6 static Callable<Object> callable(Runnable task) 7 // 返回 Callable 對象,調用它時可運行給定的任務並返回給定的結果。 8 static <T> Callable<T> callable(Runnable task, T result) 9 // 返回用於創建新線程的默認線程工廠。 10 static ThreadFactory defaultThreadFactory() 11 // 創建一個可根據需要創建新線程的線程池,但是在以前構造的線程可用時將重用它們。 12 static ExecutorService newCachedThreadPool() 13 // 創建一個可根據需要創建新線程的線程池,但是在以前構造的線程可用時將重用它們,並在需要時使用提供的 ThreadFactory 創建新線程。 14 static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) 15 // 創建一個可重用固定線程數的線程池,以共享的無界隊列方式來運行這些線程。 16 static ExecutorService newFixedThreadPool(int nThreads) 17 // 創建一個可重用固定線程數的線程池,以共享的無界隊列方式來運行這些線程,在需要時使用提供的 ThreadFactory 創建新線程。 18 static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) 19 // 創建一個線程池,它可安排在給定延遲后運行命令或者定期地執行。 20 static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) 21 // 創建一個線程池,它可安排在給定延遲后運行命令或者定期地執行。 22 static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) 23 // 創建一個使用單個 worker 線程的 Executor,以無界隊列方式來運行該線程。 24 static ExecutorService newSingleThreadExecutor() 25 // 創建一個使用單個 worker 線程的 Executor,以無界隊列方式來運行該線程,並在需要時使用提供的 ThreadFactory 創建新線程。 26 static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) 27 // 創建一個單線程執行程序,它可安排在給定延遲后運行命令或者定期地執行。 28 static ScheduledExecutorService newSingleThreadScheduledExecutor() 29 // 創建一個單線程執行程序,它可安排在給定延遲后運行命令或者定期地執行。 30 static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) 31 // 返回 Callable 對象,調用它時可在當前的訪問控制上下文中執行給定的 callable 對象。 32 static <T> Callable<T> privilegedCallable(Callable<T> callable) 33 // 返回 Callable 對象,調用它時可在當前的訪問控制上下文中,使用當前上下文類加載器作為上下文類加載器來執行給定的 callable 對象。 34 static <T> Callable<T> privilegedCallableUsingCurrentClassLoader(Callable<T> callable) 35 // 返回用於創建新線程的線程工廠,這些新線程與當前線程具有相同的權限。 36 static ThreadFactory privilegedThreadFactory() 37 // 返回一個將所有已定義的 ExecutorService 方法委托給指定執行程序的對象,但是使用強制轉換可能無法訪問其他方法。 38 static ExecutorService unconfigurableExecutorService(ExecutorService executor) 39 // 返回一個將所有已定義的 ExecutorService 方法委托給指定執行程序的對象,但是使用強制轉換可能無法訪問其他方法。 40 static ScheduledExecutorService unconfigurableScheduledExecutorService(ScheduledExecutorService executor)
線程池示例
下面通過示例來對線程池的使用做簡單演示。
1 import java.util.concurrent.Executors; 2 import java.util.concurrent.ExecutorService; 3 4 public class ThreadPoolDemo1 { 5 6 public static void main(String[] args) { 7 // 創建一個可重用固定線程數的線程池 8 ExecutorService pool = Executors.newFixedThreadPool(2); 9 // 創建實現了Runnable接口對象,Thread對象當然也實現了Runnable接口 10 Thread ta = new MyThread(); 11 Thread tb = new MyThread(); 12 Thread tc = new MyThread(); 13 Thread td = new MyThread(); 14 Thread te = new MyThread(); 15 // 將線程放入池中進行執行 16 pool.execute(ta); 17 pool.execute(tb); 18 pool.execute(tc); 19 pool.execute(td); 20 pool.execute(te); 21 // 關閉線程池 22 pool.shutdown(); 23 } 24 } 25 26 class MyThread extends Thread { 27 28 @Override 29 public void run() { 30 System.out.println(Thread.currentThread().getName()+ " is running."); 31 } 32 }
運行結果:
pool-1-thread-1 is running. pool-1-thread-2 is running. pool-1-thread-1 is running. pool-1-thread-2 is running. pool-1-thread-1 is running.
結果說明:
主線程中創建了線程池pool,線程池的容量是2。即,線程池中最多能同時運行2個線程。
緊接着,將ta,tb,tc,td,te這3個線程添加到線程池中運行。
最后,通過shutdown()關閉線程池。
更多內容