CPU密集型和IO密集型(判断最大核心线程的最大线程数)


CPU密集型和IO密集型(判断最大核心线程的最大线程数)

CPU密集型

1.CPU密集型
获取电脑CPU的最大核数,几核,最大线程数就是几
Runtime.getRuntime().availableProcessors()--->获取电脑的CPU核数

IO密集型

2.IO密集型
判断程序中,十分耗IO的线程,最大线程一般设置成大于大型IO项目的两倍

 

代码实现

public class Demo02 {
   public static void main(String[] args) {
       System.out.println(Runtime.getRuntime().availableProcessors());
       ExecutorService threadPool = new ThreadPoolExecutor(
               2,
               Runtime.getRuntime().availableProcessors(),//最大核心核心线程数
               3,
               TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
               Executors.defaultThreadFactory(),
               new ThreadPoolExecutor.DiscardOldestPolicy()
              );
       //最大承载数:Deque+Max
       for (int i = 1; i <=3; i++) {
         threadPool.execute(()-> {
             System.out.println(Thread.currentThread().getName()+": "+"OK");
        });
      }
      threadPool.shutdown();
  }
}
 

 

JUC