温馨提示×

java如何调用自定义线程池

小亿
82
2024-04-22 18:06:45
栏目: 编程语言

要调用自定义线程池,首先需要定义一个自定义的线程池类,继承自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()方法来关闭线程池。

0