共計 577 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,線程池可以使用以下兩種方法來創建:
- 使用
Executors
類中的靜態方法來創建線程池:
ExecutorService executor = Executors.newFixedThreadPool(10);
上面的代碼將創建一個固定大小為 10 的線程池。
- 使用
ThreadPoolExecutor
類來創建線程池:
int corePoolSize = 5;
int maxPoolSize = 10;
long keepAliveTime = 5000; // 線程的最大空閑時間
TimeUnit unit = TimeUnit.MILLISECONDS; // 時間單位
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(100); // 任務隊列
ExecutorService executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, unit, workQueue);
上面的代碼將創建一個核心線程數為 5,最大線程數為 10,空閑時間為 5000 毫秒的線程池,并使用一個大小為 100 的數組阻塞隊列作為任務隊列。
無論使用哪種方法創建線程池,都需要使用 ExecutorService
接口來操作線程池,如提交任務、關閉線程池等。
丸趣 TV 網 – 提供最優質的資源集合!
正文完
發表至: Java
2023-12-16