ThreadPoolExecutor
常用線程池:
Executor,ExecutorService, Future, Callable, Executors, FixedThreadPool, CachedThreadPool,
ScheduledThreadPool, SingleThreadExceutor, ForkJoinPool, WorkStealingPool, ThreadPoolExecutor
線程池底層實現。除 ForkJoinPool 外,其他常用線程池底層都是使用 ThreadPoolExecutor實現的。
這裏重點講解 ThreadPoolExecutor 線程池
重點理解線程池參數:
int corePoolSize: 核心容量,創建線程池的時候,默認有多少線程。也是線程池保持的最少線程數
int maximumPoolSize:最大容量,線程池最多有多少線程
long keepAliveTime:生命週期,0 爲永久。當線程空閒多久後,自動回收。
TimeUnit unit: 生命週期單位,爲生命週期提供單位,如:秒,毫秒、
BlockingQueue<Runnable> workQueue :任務隊列,阻塞隊列。注意,泛型必須是Runnable
本章主要是幫助快速使用ThreadPoolExecutor進行開發,以下以一個經典簡單案例幫助理解和使用ThreadPoolExecutor
/**
* 線程池
* 固定容量線程池
*/
package concurrent.t08;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Test_09_ThreadPoolExecutor {
public static void main(String[] args) {
// 模擬fixedThreadPool, 核心線程5個,最大容量5個,線程的生命週期無限。
ExecutorService service =
new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
for(int i = 0; i < 6; i++){
service.execute(new Runnable() {
@Override
public void run() {
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " - test executor");
}
});
}
System.out.println(service);
service.shutdown();
System.out.println(service.isTerminated());
System.out.println(service.isShutdown());
System.out.println(service);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
service.shutdown();
System.out.println(service.isTerminated());
System.out.println(service.isShutdown());
System.out.println(service);
}
}