The Number Of ThreadPoolExecutor

preamble

Sort out the basis for how to set the number of threads in the Java thread pool

Giant Shoulders:

  1. https://blog.csdn.net/weilaizhixing007/article/details/125955693

  1. https://blog.csdn.net/yuyan_jia/article/details/120298564#:~:text=%E4%B8%80%E4%B8%AA%E7%BA%BF%E7%A8%8B%E6%B1%A0%E5%A4%84%E7%90%86%E8%AE%A1,N%3D16%E4%B8%AA%E7%BA%BF%E7%A8%8B%E3%80%82

Begin

Based on the above description, we can understand that setting the number of thread pools needs to be classified according to the type of business operation. There are differences in the rules for setting the number of threads in different types of thread pools. It also shows that thread pools for different businesses should be created separately instead of A thread pool is applied to all types of computing tasks [email protected]

So thread pool classification:

  • Computationally intensive

  • I/O intensive

  • Computing & I/O Hybrid

Computationally intensive

The optimal number of CPUs is: number of cores+1

This kind of task mainly consumes CPU resources, and the number of threads can be set to N (number of CPU cores) + 1. One thread more than the number of CPU cores is to prevent occasional page fault interruption of threads, or tasks caused by other reasons The impact of the suspension. Once the task is suspended, the CPU is idle, and in this case an extra thread can make full use of the CPU's idle time. ---The purpose of one more thread is to solve the sudden interruption of the thread, and the CPU is not fully utilized

When the number of threads is too small, a large number of requests will be blocked in the thread queue waiting for the execution thread at the same time, and the CPU is not fully utilized at this time; when the number of threads is too large, the created execution threads are fighting for CPU resources at the same time, which will cause A large number of context switches increase the execution time of threads and affect the overall execution efficiency.

I/O dense type

The optimal number of CPUs is:

如上的算法是知道cpu利用率的情况下的算法,如下的算法是在不知道的情况下默认设置的一个算法

系统会用大部分的时间来处理 I/O 交互,而线程在处理 I/O 的时间段内不会占用 CPU 来处理,这时就可以将 CPU 交出给其它线程使用。因此在 I/O 密集型任务的应用中,我们可以多配置一些线程, 具体的计算方法是 2N。

混合型

在一个任务既有I/O密集型又有计算密集型的计算任务时,且不能分开,则线程池的参数设置.

计算操作需要5ms,DB操作需要100ms,对于一台8个CPU的服务器,怎么设置线程数呢

最优线程数 = N(CPU 核数)*(1/(UT(线程CUP利用时间)/AT(线程总时间)))

如上 wt/st就是 5/105 表示,处理此类类型的业务单个线程的CPU利用率.

1 /(UT(线程CUP利用时间)/AT(线程总时间)) : 表示 让一个内核所有时间都有事情做,需要多少个线程,这个是最多多少个线程,因为线程不是刚好就衔接CPU的占用,肯定有CPU的抢夺,还有线程的阻塞

N(CPU 核数)*(1/(UT(线程CUP利用时间)/AT(线程总时间))) 最后乘以N则标识充分利用N个内核的CUP时间需要的线程数

我们可以通过jvisualvm.exe来获取线程CPU的占有时间,如下图所示:

Guess you like

Origin blog.csdn.net/cuiyaonan2000/article/details/129009449