100~10000 的短任务 (3 秒),半个小时完成,线程池起多少个线程比较合适?用哪个线程池实例对象
一个线程半个小时内最多可完成多少任务计算: 30*60/3 = 600 个任务
对应的最大线程数: 10000/600 = 16.7 个线程
对应的 100 个短任务,按照计算只需一个线程即可
使用 ThreadPoolExecutor 进行创建,corePoolSize 设置为 3,maximumPoolSize 设置为 20,keepAliveTime 设置为 5 秒
再考虑下 当前任务是 IO 密集型 (2n+1) 的还是计算密集型的 (1.8 之前 n+1), 计算出对应的 CPU 核数
public static void main(String[] args) {
int corePoolSize = 3;
int maximumPoolSize = 20;
long keepAliveTime = 5;
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
keepAliveTime, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
}
});
}
ExecutorService executorService = Executors.newCachedThreadPool();
实际调用的就是 ThreadPoolExecutor类方法,只是默认做了一层封装
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}