Detailed explanation of the use of Java thread pool

Previous:

Thread-safe collections in Java

Thread Pool

The thread pool is also a class provided in the JUC package, why should there be a thread pool?

To give an example:
During the running of the program, there will be 100 tasks to be executed at the same time. According to the previous writing method, we will create 100 threads. After the execution is completed, the threads will be destroyed.
If there are another 500 tasks, then we will create another 500 threads and destroy them after execution.
Regardless of whether our device can create this multi-thread at the same time, it is a waste of resources to simply destroy it when it is used up, and create this action again when a new task comes. Therefore, we can use the thread pool to solve this problem.

The thread pool is to create some threads in advance. If there is a task to be executed, the created thread will be executed from the pool. After the execution is completed, the thread will not be destroyed, but returned to the thread pool. The next task comes. Then use it.

The main benefits of using a thread pool are as follows :

  • Thread reuse to reduce resource consumption
  • Improve program response speed
  • Easy to manage, can control the maximum number of concurrency

ThreadPoolExecutor

First, let's take a look at the ThreadPoolExecutor class.

Guess you like

Origin blog.csdn.net/yuzhiqiang_1993/article/details/118437806