线程池的最大核心线程数到底如何设置(cpu密集型,IO密集型)
并发编程:(并发/并行)
并发:多个线程操作同一个资源
并行:多个线程一起运行(线程池就可以实现)并行是效率最高的
问题:我们如何设置这个最大核心线程数呢
思路1、CPU密集型:根据cpu的核数(是几核的就定义为几)可以保持CPU的效率最高!
如何获取cpu核数:
方式1、查看我们任务管理器,查看性能,cpu(12核)
方式2、打开电脑管理,查看设备管理器,处理器数一下有多少个(12个)
!!!方式3、我们最好不要写死里,运维要是跑服务器,服务器的核数肯定比我们多,所以我们用java的Api获取(Runtime.getRuntime().availableProcessors()),所以这里我们就代替下。
思路2、IO密集型:判断我们程序中十分耗IO的线程。(只要大于这个数就ok了)
package org.example.threadpoolexecutor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestThreadPoolExecutorThere {
public static void main(String[] args) {
// ExecutorService threadPool = Executors.newSingleThreadExecutor();//单个线程的线程池
// ExecutorService threadPool = Executors.newFixedThreadPool(5);//设定固定线程个数的线程池
ExecutorService threadPool = Executors.newCachedThreadPool();//可以随着使用的线程个数变化而而变化的线程池
try {
for (int i = 1; i <=100 ; i++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"=>ok");
});
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
threadPool.shutdown();
}
}
}