The thread pool is really set up to see what tasks your thread pools perform, cpu-intensive, IO-intensive, mixed-type, different types of tasks, and set up differently
Tasks are generally divided into: CPU-intensive, IO-intensive, hybrid, with different sizes of thread pools allocated for different types of tasks
1. CPU-Intensive
Try to use a smaller thread pool, the average CPU core number +1
Because CPU-intensive task CPU usage is high, if too many threads, can only increase the number of switch thread context, resulting in additional overhead
2, IO-intensive
Method One: You can use a larger thread pool, the average number of CPU cores * 2
IO-Intensive CPU usage is low, allowing the CPU to wait for the IO to handle other tasks, taking full advantage of CPU time
Method Two: The higher the percentage of thread wait time, the more threads are required. The higher the percentage of thread CPU time, the fewer threads are required.
Here's an example:
For example, the average CPU run time per thread is 0.5s, while the thread wait time (non-CPU run time, such as IO) is 1.5S,CPU core number 8, then according to the above formula is estimated to be: ((0.5+1.5)/0.5) *8=32. This formula is further translated into:
number of best threads = (ratio of thread wait time to thread CPU time + 1) * Number of CPUs 3, mixed type
Tasks can be divided into CPU-intensive and IO-intensive, and then processed using different thread pools, depending on the situation
How the Java thread pool is set to a reasonable size