This is the 24th day of my participation in the August Text Challenge.More challenges in August

WangScaler: A writer with heart.

Declaration: uneducated, if there is a mistake, kindly correct.

In order to reduce the memory cost of creating and destroying threads, thread pools are used to reuse threads. The most common types of thread pools are:

  • NewFixedThreadPool: a fixed number of thread pools.

  • NewSingleThreadExecutor: single-thread pool.

  • NewCachedThreadPool: cacheable thread pool.

  • NewScheduledThreadPool: A thread pool of unlimited size that can execute threads periodically and periodically.

  • NewWorkStealingPool: java8 new thread pool, it will work through the way, so that the multi-core CPU will not idle, there will always be a thread to run the CPU.

Simple to use

newFixedThreadPool

A fixed number of thread pools, and the parameter here is 3, which means that there are three threads that can execute tasks, one thread for each task submitted, and when the number of tasks reaches the number of threads, new tasks are queued.

We have five tasks, so when three threads are performing three tasks, the remaining two tasks go into wait and wait for one thread to complete before executing the remaining tasks.

package com.wangscaler.thread;
​
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
​
​
/ * * *@author WangScaler
 * @date2021/8/23 14:00 * /public class ThreadPool {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        try {
            for (int i = 0; i < 5; i++) { pool.execute(() -> System.out.println(Thread.currentThread().getName()) ); }}catch (Exception e) {
            e.printStackTrace();
        } finally{ pool.shutdown(); }}}Copy the code

The result is as follows:

pool-1-thread-1
pool-1-thread-3
pool-1-thread-2
pool-1-thread-3
pool-1-thread-1
Copy the code

Suitable for long-term missions.

newSingleThreadExecutor

A single thread pool, so there is only one thread executing the task from start to finish.

The above code ExecutorService pool = Executors. NewFixedThreadPool (3); Replace the ExecutorService pool = Executors. NewSingleThreadExecutor (); The result is as follows:

pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
Copy the code

Only thread 1 performs the task throughout, confirming that this is a single-threaded thread pool. Suitable for the scenario where one task at a time is executed.

newCachedThreadPool

When the number of threads in the thread pool exceeds the number of tasks, some idle threads (60 seconds of non-executing threads) are reclaimed. When the number of tasks increases, new threads are created to execute tasks.

The above code Executors. NewFixedThreadPool (3); Replace Executors. NewCachedThreadPool ();

The result is as follows:

pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-5
Copy the code

Five new threads are created to execute the task. How many threads are created to execute the task if we add sleep to the above thread task?

package com.wangscaler.thread;
​
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
​
​
/ * * *@author WangScaler
 * @date2021/8/23 14:00 * /public class ThreadPool {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newCachedThreadPool();
        try {
            for (int i = 0; i < 5; i++) {
                pool.execute(() -> System.out.println(Thread.currentThread().getName())
                );
                TimeUnit.SECONDS.sleep(1); }}catch (Exception e) {
            e.printStackTrace();
        } finally{ pool.shutdown(); }}}Copy the code

Execute the above code again and find that the result is not the same as last time.

pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
pool-1-thread-1
Copy the code

This is a cacheable thread pool that dynamically manages the number of threads based on the number of tasks. Suitable for performing many short asynchronous applets or for lightly loaded servers.

The above method is only for demonstration use. It is not recommended to create a thread pool in this way in real development. This will be explained in the next article.

Seven parameters

  • CorePoolSize: indicates the number of core threads. When the number of core threads is reached, the task will enter the workQueue for waiting.

  • MaximumPoolSize: specifies the maximum number of concurrent threads that can be executed in a thread pool. Note that this value must be greater than or equal to 1.

  • KeepAliveTime: indicates the lifetime of extra idle threads. When the current thread pool exceeds corePoolSize, when the keepAliveTime value is reached, the excess idle threads are destroyed until there are only corePoolSize threads left.

  • 4. Unit: keepAliveTime unit.

  • WorkQueue: A queue of submitted tasks that have not yet been executed.

  • ThreadFactory: represents a threadFactory that generates worker threads in the thread pool and is used to create threads.

  • Handler: Reject policy. This policy specifies how to reject Runnable requests when the queue is full and the number of worker threads is greater than or equal to the maximum thread pool size (maximumPoolSize).

Implementation process

  • 1. After creating the thread pool, wait for the task.

  • 2. When execute() is called.

    • If the number of running threads is less than the number of corePoolSize core threads, a thread is created to execute the task

    • If the number of running threads is not smaller than corePoolSize and the workQueue task queue is not full, the task is added to the workQueue task queue.

    • If the task queue is also full and the number of threads running at this time is less than the maximum number of threads maximumPoolSize, a new thread is created immediately to execute the task. (Note: instead of executing tasks in the task queue and adding new tasks to the task queue)

    • If the number of running threads is also greater than the maximum number of maximumPoolSize threads, the thread pool will enable handler saturation denial.

  • 3. When the thread has finished executing the task, it will fetch a new task from the workQueue and continue executing it.

  • 4. If the thread is idle (i.e., no task is executed)

    • If the number of threads in the thread pool is greater than the number of corePoolSize core threads, the threads that exceed the keepAliveTime idle lifetime are deregixed and recycled.

    • In this case, the number of threads in the thread pool is not greater than the number of core threads.

The whole flow chart is roughly as follows: Do not spray for non-professional drawing.

Today I will write here, tomorrow from the point of view of the source thread execution process.

Come all come, click “like” and then go!

Follow WangScaler and wish you a promotion, a raise and no bucket!