十七、ThreadPoolExecutor執行緒池
阿新 • • 發佈:2018-12-24
一、簡介
JDK的Executor框架的實現類ThreadPoolExecutor,實現了Executor介面和ExecutorService介面。
ThreadPoolExecutor執行過程如下:
1)判斷corePoolSize是否都執行中,如果不是那麼直接執行任務。
2)判斷緩衝佇列是否滿了,如果不是那麼加入緩衝佇列
3)判斷是否超過maxNumPoolSize,如果不是那麼建立執行緒執行任務。
4)如果超過maxNumPoolSize那麼呼叫RejectedExecutionHandler
JDK文件:http://tool.oschina.net/uploads/apidocs/jdk-zh/java/util/concurrent/ThreadPoolExecutor.html
二、程式碼示例
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class ThreadPoolExecutorDemo { private static ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());public static void main(String[] args) { // 提交執行緒 executor.submit(() -> System.out.println("running")); System.out.println("end"); } }