要調用自定義線程池,首先需要定義一個自定義的線程池類,繼承自java.util.concurrent.ThreadPoolExecutor類。然后在自定義的線程池類中重寫構造方法,設置線程池的核心線程數、最大線程數、線程空閑時間、任務隊列等參數。
接下來可以通過創建一個實例化自定義線程池類,并調用execute()方法來提交任務給線程池執行。例如:
public class CustomThreadPool extends ThreadPoolExecutor {
public CustomThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
public static void main(String[] args) {
CustomThreadPool customThreadPool = new CustomThreadPool(5, 10, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
for (int i = 0; i < 10; i++) {
customThreadPool.execute(new MyTask(i));
}
customThreadPool.shutdown();
}
static class MyTask implements Runnable {
private int taskId;
public MyTask(int taskId) {
this.taskId = taskId;
}
@Override
public void run() {
System.out.println("Task " + taskId + " is running on thread " + Thread.currentThread().getName());
}
}
}
在上面的例子中,我們創建了一個CustomThreadPool類,重寫了構造方法并定義了一個main()方法來使用自定義線程池。我們提交了10個任務給線程池執行,并最后調用shutdown()方法來關閉線程池。