Detailed explanation of the use of Java thread pool

In the previous articles, Xiaoqian explained to friends what a thread is and several ways to create a thread. This is where my friend asked, the thread pool is the most used in our work, Xiaoqian, can you tell us more about the thread pool? Now that the friends have raised their needs, Xiaoqian, I have to satisfy everyone. Today I will talk about the thread pool for the friends!

picture

 1. Thread pool

1. What is a thread pool

In object-oriented programming, creating and destroying objects is very time-consuming, because creating an object requires more memory resources and other resources. This is even more so in Java, where the virtual machine tries to keep track of every object so that it can be garbage collected after the object is destroyed. One way to improve the efficiency of service programs is to reduce the number of object creation and destruction as much as possible, especially the object creation and destruction processes that consume a lot of resources. This is the reason for the "pooling resource" technology.

The thread pool, as the name suggests, is to create several executable threads in advance and put them into a pool (container). When we need them, we can directly get threads from the pool without creating them ourselves. After using them, we don’t need to destroy the threads but put them back into the pool. Thereby reducing the overhead of creating and destroying thread objects.

The role of thread pool

The existence of the thread pool reduces the number of threads created and destroyed, and each worker thread can be reused to perform multiple tasks. In addition, we can adjust the number of worker threads in the thread pool according to the capacity of the system to prevent the server from being exhausted due to excessive memory consumption.

How to create a thread pool

There are also many ways to create thread pools, each of which corresponds to different usage scenarios. Generally speaking, the creation of thread pools can be divided into the following two categories:

The first is to manually create a thread pool through ThreadPoolExecutor;

The second is to automatically create a thread pool through Executors.

3.1 ThreadPoolExecutor

ThreadPoolExecutor is the most basic and recommended way to manually create a thread pool. It can provide up to 7 parameter settings when creating it. An example of using ThreadPoolExecutor is as follows:

// 创建线程池
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 10, 100, TimeUnit.SECONDS, new LinkedBlockingQueue<>(10));
// 执行任务
for (int i = 0; i < 10; i++) {
    int index = i;
    threadPool.execute(() -> {
        System.out.println(index + " 被执行,线程名:" + Thread.currentThread().getName());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });
}

The execution result of the above program is shown in the figure below:

3.2 Executors

Through the automatic creation of thread pools by Executors, we have the following implementation methods:

Executors.newFixedThreadPool

Create a thread pool with a fixed size, which can control the number of concurrent threads, and the excess threads will wait in the queue.

Executors.newCachedThreadPool

Create a cacheable thread pool. If the number of threads exceeds the processing requirements, the cache will be recycled after a period of time. If the number of threads is not enough, new threads will be created.

Executors.newSingleThreadExecutor

Create a thread pool with a single number of threads, which can guarantee the execution order of first-in-first-out.

Executors.newScheduledThreadPool

Create a thread pool that can execute delayed tasks.

Executors.newSingleThreadScheduledExecutor

Create a single-threaded thread pool that can execute delayed tasks.

Executors.newWorkStealingPool

Create a thread pool for preemptive execution (task execution order is uncertain)

The above are several implementation methods of actuators. If you want to know more details, you can private message Xiaoqian. Boge can answer you in more detail!

picture

 2. Summary

Through Xiaoqian's explanation today, I don't know if the friends have some understanding of the role of the thread pool and how to create it manually. In addition, in Alibaba's Java development manual, their internal employees are forced to manually create thread pools, which shows the benefits of manually creating thread pools.

Guess you like

Origin blog.csdn.net/GUDUzhongliang/article/details/132065792