CPU密集orIO密集or混合型
)看应用是CPU密集型的仍是IO密集型的,仍是混合型的。segmentfault
CPU密集
CPU密集型的话,通常配置CPU处理器个数+/-1个线程,所谓CPU密集型就是指系统大部分时间是在作程序正常的计算任务,例如数字运算、赋值、分配内存、内存拷贝、循环、查找、排序等,这些处理都须要CPU来完成。线程
IO密集
IO密集型的话,是指系统大部分时间在跟I/O交互,而这个时间线程不会占用CPU来处理,即在这个时间范围内,能够由其余线程来使用CPU,于是能够多配置一些线程。code
混合型
混合型的话,是指二者都占有必定的时间。排序
/** * Support class for thread pool size * * @author Nadeem Mohammad * */ public final class ThreadPoolUtil { private ThreadPoolUtil() { } /** * Each tasks blocks 90% of the time, and works only 10% of its * lifetime. That is, I/O intensive pool * @return io intesive Thread pool size */ public static int ioIntesivePoolSize() { double blockingCoefficient = 0.9; return poolSize(blockingCoefficient); } /** * * Number of threads = Number of Available Cores / (1 - Blocking * Coefficient) where the blocking coefficient is between 0 and 1. * * A computation-intensive task has a blocking coefficient of 0, whereas an * IO-intensive task has a value close to 1, * so we don't have to worry about the value reaching 1. * @param blockingCoefficient the coefficient * @return Thread pool size */ public static int poolSize(double blockingCoefficient) { int numberOfCores = Runtime.getRuntime().availableProcessors(); int poolSize = (int) (numberOfCores / (1 - blockingCoefficient)); return poolSize; } }
ExecutorService executorService = Executors.newFixedThreadPool(ThreadPoolUtil.ioIntesivePoolSize());
这样语义化设置,表达能力强一些。内存