java線程池創(chuàng)建的方法是什么

小億
93
2023-10-24 21:19:59

在Java中,線程池可以使用以下兩種方法來(lái)創(chuàng)建:

  1. 使用Executors類中的靜態(tài)方法來(lái)創(chuàng)建線程池:
ExecutorService executor = Executors.newFixedThreadPool(10);

上面的代碼將創(chuàng)建一個(gè)固定大小為10的線程池。

  1. 使用ThreadPoolExecutor類來(lái)創(chuàng)建線程池:
int corePoolSize = 5;
int maxPoolSize = 10;
long keepAliveTime = 5000; // 線程的最大空閑時(shí)間
TimeUnit unit = TimeUnit.MILLISECONDS; // 時(shí)間單位
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(100); // 任務(wù)隊(duì)列

ExecutorService executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, unit, workQueue);

上面的代碼將創(chuàng)建一個(gè)核心線程數(shù)為5,最大線程數(shù)為10,空閑時(shí)間為5000毫秒的線程池,并使用一個(gè)大小為100的數(shù)組阻塞隊(duì)列作為任務(wù)隊(duì)列。

無(wú)論使用哪種方法創(chuàng)建線程池,都需要使用ExecutorService接口來(lái)操作線程池,如提交任務(wù)、關(guān)閉線程池等。

0