線程池的概念:
線程池的基本思想還是一種對象池的思想,開辟一塊內存空間,里面存放了眾多(未死亡)的線程,池中線程執行調度由池管理器來處理。當有線程任務時,從池中取一個,執行完成后線程對象歸池,這樣可以避免反復創建線程對象所帶來的性能開銷,節省了系統的資源。
(舉個簡單的例子,線程池就相當於一個水池又或者是一個筆筒,里面放着很多的筆,當有線程任務的時候,就從筆筒去除,用完之后就再次放入進去。)
個人理解:
1、在Java5之前,要實現一個線程池是相當有難度的,現在Java5為我們做好了一切,我們只需要按照提供的API來使用,即可享受線程池帶來的極大便利。
2、Java5的線程池分好多種:具體的可以分為兩類,固定尺寸的線程池、可變尺寸連接池。
3、在使用線程池之前,必須知道如何去創建一個線程池,在Java5中,需要了解java.util.concurrent.Executors類的API,這個類提供大量創建連接池的靜態方法,是必須掌握的。
一、固定大小的線程池,newFixedThreadPool:
package app.executors; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; /** * Java線程:線程池 * * @author 馮小衛 */ public class Test { public static void main(String[] args) { // 創建一個可重用固定線程數的線程池 ExecutorService pool = Executors.newFixedThreadPool(5); // 創建線程 Thread t1 = new MyThread(); Thread t2 = new MyThread(); Thread t3 = new MyThread(); Thread t4 = new MyThread(); Thread t5 = new MyThread(); // 將線程放入池中進行執行 pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); // 關閉線程池 pool.shutdown(); } } class MyThread extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName() + "正在執行。。。"); } }
輸出結果:
pool-1-thread-1正在執行。。。 pool-1-thread-3正在執行。。。 pool-1-thread-4正在執行。。。 pool-1-thread-2正在執行。。。 pool-1-thread-5正在執行。。。
改變ExecutorService pool = Executors.newFixedThreadPool(5)中的參數:ExecutorService pool = Executors.newFixedThreadPool(2),輸出結果是:
pool-1-thread-1正在執行。。。 pool-1-thread-1正在執行。。。 pool-1-thread-2正在執行。。。 pool-1-thread-1正在執行。。。 pool-1-thread-2正在執行。。。
從以上結果可以看出,newFixedThreadPool的參數指定了可以運行的線程的最大數目,超過這個數目的線程加進去以后,不會運行。其次,加入線程池的線程屬於托管狀態,線程的運行不受加入順序的影響。
二、單任務線程池,newSingleThreadExecutor:
僅僅是把上述代碼中的ExecutorService pool = Executors.newFixedThreadPool(2)改為ExecutorService pool = Executors.newSingleThreadExecutor();
輸出結果:
pool-1-thread-1正在執行。。。 pool-1-thread-1正在執行。。。 pool-1-thread-1正在執行。。。 pool-1-thread-1正在執行。。。 pool-1-thread-1正在執行。。。
可以看出,每次調用execute方法,其實最后都是調用了thread-1的run方法。
三、可變尺寸的線程池,newCachedThreadPool:
與上面的類似,只是改動下pool的創建方式:ExecutorService pool = Executors.newCachedThreadPool();
輸出:
pool-1-thread-1正在執行。。。 pool-1-thread-2正在執行。。。 pool-1-thread-4正在執行。。。 pool-1-thread-3正在執行。。。 pool-1-thread-5正在執行。。。
這種方式的特點是:可根據需要創建新線程的線程池,但是在以前構造的線程可用時將重用它們。
四、延遲連接池,newScheduledThreadPool:
package app.executors; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * Java線程:線程池 * */ public class Test { public static void main(String[] args) { // 創建一個線程池,它可安排在給定延遲后運行命令或者定期地執行。 ScheduledExecutorService pool = Executors.newScheduledThreadPool(2); // 創建實現了Runnable接口對象,Thread對象當然也實現了Runnable接口 Thread t1 = new MyThread(); Thread t2 = new MyThread(); Thread t3 = new MyThread(); // 將線程放入池中進行執行 pool.execute(t1); // 使用延遲執行風格的方法 pool.schedule(t2, 1000, TimeUnit.MILLISECONDS); pool.schedule(t3, 10, TimeUnit.MILLISECONDS); // 關閉線程池 pool.shutdown(); } } class MyThread extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName() + "正在執行。。。"); } }
ExecutorService:
是一個接口,繼承了Executor:
public interface ExecutorService extends Executor { }
而Executor亦是一個接口,該接口只包含了一個方法:
void execute(Runnable command);
該類是一個輔助類,此包中所定義的 Executor、ExecutorService、ScheduledExecutorService、ThreadFactory 和 Callable 類的工廠和實用方法。
此類支持以下各種方法:
newFixedThreadPool()
創建一個可重用固定線程數的線程池,以共享的無界隊列方式來運行這些線程。
shutdown
void shutdown() 啟動一次順序關閉,執行以前提交的任務,但不接受新任務。如果已經關閉,則調用沒有其他作用。 拋出: SecurityException - 如果安全管理器存在並且關閉,此 ExecutorService 可能操作某些不允許調用者修改的線程(因為它沒有保持 RuntimePermission("modifyThread")),或者安全管理器的 checkAccess 方法拒絕訪問。 啟動一次順序關閉,執行以前提交的任務,但不接受新任務。如果已經關閉,則調用沒有其他作用。
awaitTermination
boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException 請求關閉、發生超時或者當前線程中斷,無論哪一個首先發生之后,都將導致阻塞,直到所有任務完成執行。 參數: timeout - 最長等待時間 unit - timeout 參數的時間單位 返回: 如果此執行程序終止,則返回 true;如果終止前超時期滿,則返回 false 拋出: InterruptedException - 如果等待時發生中斷 請求關閉、發生超時或者當前線程中斷,無論哪一個首先發生之后,都將導致阻塞,直到所有任務完成執行。既是等待所有子線程執行結束。
execute
void execute(Runnable command)
-
在未來某個時間執行給定的命令。該命令可能在新的線程、已入池的線程或者正調用的線程中執行,這由
Executor實現決定。
-
- 參數:
-
command
- 可運行的任務 - 拋出:
-
RejectedExecutionException
- 如果不能接受執行此任務。 -
NullPointerException
- 如果命令為 null
在未來某個時間執行給定的命令。該命令可能在新的線程、已入池的線程或者正調用的線程中執行,這由 Executor 實現決定。
submit
Future<?> submit(Runnable task) 提交一個 Runnable 任務用於執行,並返回一個表示該任務的 Future。該 Future 的 get 方法在成功 完成時將會返回 null。 參數: task - 要提交的任務 返回: 表示任務等待完成的 Future 拋出: RejectedExecutionException - 如果任務無法安排執行 NullPointerException - 如果該任務為 null 提交一個 Runnable 任務用於執行,並返回一個表示該任務的 Future。該 Future 的 get 方法在成功 完成時將會返回 null。
public class ExecutorServiceTest { public static void main(String[] args) throws IOException, InterruptedException { // 創建一個固定大小的線程池 ExecutorService service = Executors.newFixedThreadPool(3); for (int i = 0; i < 10; i++) { System.out.println("創建線程" + i); Runnable run = new Runnable() { @Override public void run() { System.out.println("啟動線程"); } }; // 在未來某個時間執行給定的命令 service.execute(run); } // 關閉啟動線程 service.shutdown(); // 等待子線程結束,再繼續執行下面的代碼 service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); System.out.println("all thread complete"); } }
可以發現線程被循環創建,但是啟動線程卻不是連續的,而是由ExecutorService決定的。