Java 線程池管理多個工作線程,其中包含了一個隊列,包含着所有等待被執行的任務。開發者可以通過使用ThreadPoolExecutor
來在Java中創建線程池。
線程池是Java中多線程的一個重要概念,因爲通過
Thread
模型來控制多線程是非常麻煩以及易錯的一個過程。過多的釋放線程會造成線程調度的變慢以及過度的消耗內存。而頻繁的創建線程,也沒有很好的複用線程,所以有了線程池的概念。Java中的線程池就是ExecutorService
。
其中包含了一些基本的關閉,執行等功能
ExecutorService舉例
java.util.concurrent.Executors
提供了java.util.concurrent.Executor
接口的實現,並且用來提供線程池服務。參考如下代碼:
package com.sapphire.threadpool;
public class WorkerThread implements Runnable {
private String command;
public WorkerThread(String s){
this.command=s;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" Start. Command = "+command);
processCommand();
System.out.println(Thread.currentThread().getName()+" End.");
}
private void processCommand() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString(){
return this.command;
}
}
上面的代碼是一個簡單的實現了Runnable
的WorkThread
。下面展示的是線程池代碼,通過Executors
框架創建的固定線程數的線程池。
package com.journaldev.threadpool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class SimpleThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
}
上面個程序中的ExecutorService executor
就是一個線程池,其調用的函數Executors.newFixedThreadPool(int size)
函數來生成固定的線程數的一個線程池。在程序中,我們通過一個for循環提交了10個任務,因爲我們配置了線程池的大小,所以其中的線程數最大始終是5不會出現無限創建線程的那種情況,當同時有其他的任務提交到線程池的時候,線程池會持續的等待,直到有一個任務完成,那麼另一個任務就會從等待隊列裏面出來,進入執行隊列來執行。
下面是上面程序的輸出內容:
pool-1-thread-2 Start. Command = 1
pool-1-thread-4 Start. Command = 3
pool-1-thread-1 Start. Command = 0
pool-1-thread-3 Start. Command = 2
pool-1-thread-5 Start. Command = 4
pool-1-thread-4 End.
pool-1-thread-5 End.
pool-1-thread-1 End.
pool-1-thread-3 End.
pool-1-thread-3 Start. Command = 8
pool-1-thread-2 End.
pool-1-thread-2 Start. Command = 9
pool-1-thread-1 Start. Command = 7
pool-1-thread-5 Start. Command = 6
pool-1-thread-4 Start. Command = 5
pool-1-thread-2 End.
pool-1-thread-4 End.
pool-1-thread-3 End.
pool-1-thread-5 End.
pool-1-thread-1 End.
Finished all threads
其中輸出的內容也說明了在線程池中有5個線程,名字從pool-1-thread-1
到pool-1-thread-5
,由叫這5個名字的線程負責執行提交到線程池的任務。
ThreadPoolExecutor舉例
Executors
類通過ThreadPoolExecutor
提供了ExecutorService
的簡單實現,但是,ThreadPoolExecutor
提供的特性更多。我們可以在創建ThreadPoolExecutor
時指定線程池的大小,也可以定製RejectedExecutionHandler
的實現來處理無法加入工作隊列的任務。
下面是我們的自定義的RejectedExecutionHandler
:
package com.sapphire.threadpool;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
public class RejectedExecutionHandlerImpl implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println(r.toString() + " is rejected");
}
}
ThreadPoolExecutor
會提供一些方法,令開發者可以知道目前線程池的狀態,比如,線程池大小,活躍的線程數,任務隊列長度等信息。所以,下面我寫了一個監控線程來定期展示線程池的狀態信息。
package com.sapphire.threadpool;
import java.util.concurrent.ThreadPoolExecutor;
public class MyMonitorThread implements Runnable
{
private ThreadPoolExecutor executor;
private int seconds;
private boolean run=true;
public MyMonitorThread(ThreadPoolExecutor executor, int delay)
{
this.executor = executor;
this.seconds=delay;
}
public void shutdown(){
this.run=false;
}
@Override
public void run()
{
while(run){
System.out.println(
String.format("[monitor] [%d/%d] Active: %d, Completed: %d, Task: %d, isShutdown: %s, isTerminated: %s",
this.executor.getPoolSize(),
this.executor.getCorePoolSize(),
this.executor.getActiveCount(),
this.executor.getCompletedTaskCount(),
this.executor.getTaskCount(),
this.executor.isShutdown(),
this.executor.isTerminated()));
try {
Thread.sleep(seconds*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
下面是使用ThreadPoolExecutor
的實現方案。
package com.sapphire.threadpool;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class WorkerPool {
public static void main(String args[]) throws InterruptedException{
//RejectedExecutionHandler implementation
RejectedExecutionHandlerImpl rejectionHandler = new RejectedExecutionHandlerImpl();
//Get the ThreadFactory implementation to use
ThreadFactory threadFactory = Executors.defaultThreadFactory();
//creating the ThreadPoolExecutor
ThreadPoolExecutor executorPool = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2), threadFactory, rejectionHandler);
//start the monitoring thread
MyMonitorThread monitor = new MyMonitorThread(executorPool, 3);
Thread monitorThread = new Thread(monitor);
monitorThread.start();
//submit work to the thread pool
for(int i=0; i<10; i++){
executorPool.execute(new WorkerThread("cmd"+i));
}
Thread.sleep(30000);
//shut down the pool
executorPool.shutdown();
//shut down the monitor thread
Thread.sleep(5000);
monitor.shutdown();
}
}
需要注意的是,當我們在創建ThreadPoolExecutor
的時候,我們限制了線程池的大小最小爲2,最大大小爲4,而工作隊列長度爲2。所以如果線程池中4個運行的任務的時候,再提交更多任務的時候,則至多隻能提交兩個處於等待狀態的任務。如果再提交更多的話,則會由RejectedExecutionHandlerImpl
來處理。
cmd8 is rejected
cmd9 is rejected
[monitor] [0/2] Active: 4, Completed: 0, Task: 6, isShutdown: false, isTerminated: false
[monitor] [4/2] Active: 4, Completed: 0, Task: 6, isShutdown: false, isTerminated: false
pool-1-thread-4 End.
pool-1-thread-1 End.
pool-1-thread-2 End.
pool-1-thread-3 End.
pool-1-thread-1 Start. Command = cmd3
pool-1-thread-4 Start. Command = cmd2
[monitor] [4/2] Active: 2, Completed: 4, Task: 6, isShutdown: false, isTerminated: false
[monitor] [4/2] Active: 2, Completed: 4, Task: 6, isShutdown: false, isTerminated: false
pool-1-thread-1 End.
pool-1-thread-4 End.
[monitor] [4/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: true, isTerminated: true
[monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: true, isTerminated: true
可以觀察線程池在各個狀態,如:活躍狀態數,任務的完成數等等信息的變化。我們通過調用shutdown()
方法來結束提交任務的執行,並結束了線程池。
如果開發者希望來延遲執行一個任務,或者定期執行一個任務的話,開發者可以使用ScheduledThreadPoolExecutor
類來完成這個功能。