溫馨提示×

java線程池創建的方法是什么

小億
96
2023-10-24 21:19:59
欄目: 編程語言

在Java中,線程池可以使用以下兩種方法來創建:

  1. 使用Executors類中的靜態方法來創建線程池:
ExecutorService executor = Executors.newFixedThreadPool(10);

上面的代碼將創建一個固定大小為10的線程池。

  1. 使用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接口來操作線程池,如提交任務、關閉線程池等。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女