前面分別介紹了"Java多線程基礎"、"JUC原子類"和"JUC鎖"。本章介紹JUC的最後一部分的內容——線程池。內容包括:
線程池架構圖
線程池示例html
轉載請註明出處:http://www.cnblogs.com/skywang12345/p/3509903.htmljava
線程池的架構圖以下:多線程
1. Executor架構
它是"執行者"接口,它是來執行任務的。準確的說,Executor提供了execute()接口來執行已提交的 Runnable 任務的對象。Executor存在的目的是提供一種將"任務提交"與"任務如何運行"分離開來的機制。
它只包含一個函數接口:併發
void execute(Runnable command)
2. ExecutorServiceide
ExecutorService繼承於Executor。它是"執行者服務"接口,它是爲"執行者接口Executor"服務而存在的;準確的話,ExecutorService提供了"將任務提交給執行者的接口(submit方法)","讓執行者執行任務(invokeAll, invokeAny方法)"的接口等等。函數
ExecutorService的函數列表高併發
3. AbstractExecutorService性能
AbstractExecutorService是一個抽象類,它實現了ExecutorService接口。
AbstractExecutorService存在的目的是爲ExecutorService中的函數接口提供了默認實現。spa
AbstractExecutorService函數列表
因爲它的函數列表和ExecutorService同樣,這裏就再也不重複列舉了。
4. ThreadPoolExecutor
ThreadPoolExecutor就是大名鼎鼎的"線程池"。它繼承於AbstractExecutorService抽象類。
ThreadPoolExecutor函數列表
5. ScheduledExecutorService
ScheduledExecutorService是一個接口,它繼承于于ExecutorService。它至關於提供了"延時"和"週期執行"功能的ExecutorService。
ScheduledExecutorService提供了相應的函數接口,能夠安排任務在給定的延遲後執行,也能夠讓任務週期的執行。
ScheduledExecutorService函數列表
6. ScheduledThreadPoolExecutor
ScheduledThreadPoolExecutor繼承於ThreadPoolExecutor,而且實現了ScheduledExecutorService接口。它至關於提供了"延時"和"週期執行"功能的ScheduledExecutorService。
ScheduledThreadPoolExecutor相似於Timer,可是在高併發程序中,ScheduledThreadPoolExecutor的性能要優於Timer。
ScheduledThreadPoolExecutor函數列表
7. Executors
Executors是個靜態工廠類。它經過靜態工廠方法返回ExecutorService、ScheduledExecutorService、ThreadFactory 和 Callable 等類的對象。
Executors函數列表
下面經過示例來對線程池的使用作簡單演示。
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()關閉線程池。