Java 实现动态线程池
时间: 2023-02-12 17:23:17 浏览: 222
Java 实现动态线程池的方法有很多,其中一种常用的方法是使用 Executor 框架中的 ThreadPoolExecutor 类。
ThreadPoolExecutor 类提供了多种构造方法,可以根据需要调整线程池的大小和其他参数。
例如:
```
int corePoolSize = 2;
int maximumPoolSize = 4;
long keepAliveTime = 10;
TimeUnit unit = TimeUnit.SECONDS;
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(2);
ThreadFactory threadFactory = Executors.defaultThreadFactory();
RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
```
这样就可以通过 executor.execute(runnable) 来向线程池提交任务。
除此之外,还可以使用Executors 工具类中提供的 newCachedThreadPool() 和 newFixedThreadPool() 方法来创建动态线程池。