当前位置:网站首页>Talking about thread pool with pictures and texts

Talking about thread pool with pictures and texts

2022-06-10 05:28:00 Bug trendsetter

Basic composition

1、 Thread pool manager (ThreadPool): Used to create and manage thread pools , Include Creating a thread pool , Destroy thread pool , Add a new task ;
2、 The worker thread (PoolWorker): Threads in thread pool , Waiting when there is no task , You can cycle through tasks ;
3、 Task interface (Task): The interface that each task must implement , For worker threads to schedule the execution of tasks , It mainly specifies the entry of tasks , The end of the task , Task execution status, etc ;
4、 Task queue (taskQueue): Used to store unprocessed tasks . Provide a buffer mechanism .

  • Reduce resource consumption . Reduces the cost of thread creation and destruction by reusing created threads .

  • Improve response time . When the mission arrives , Tasks can be executed without waiting for thread creation .

  • Improve the manageability of threads . Uniform allocation is possible using thread pools , Tune and monitor , Delayed execution 、 Strategy of timing cycle execution, etc .

0558a6712e9d5f91f69ce02979656a3f.png

java.uitl.concurrent.ThreadPoolExecutor Class is the most core class in the thread pool

Construction parameters

java.uitl.concurrent.ThreadPoolExecutor Class is the most core class in the thread pool 


 Construction parameters 
public ThreadPoolExecutor(
   int corePoolSize, // The maximum number of core threads in the thread pool . When a thread pool creates a new thread , If the current total number of threads is less than corePoolSize, The core thread is created , If exceeded corePoolSize, The new thread is a non core thread    By default, core threads live in the thread pool all the time , Even if this core thread does nothing ( Idle state ). If specified ThreadPoolExecutor Of allowCoreThreadTimeOut This property is true, So if the core thread doesn't work ( Idle state ) Words , Over a certain period of time ( The duration is determined by the following parameters ), Will be destroyed   
   int maximumPoolSize,//( The maximum number of threads that can be created when there are not enough threads ) Total threads  =  Number of core threads  +  Number of non core threads 
   long keepAliveTime, // Idle timeout of non core thread 
   TimeUnit unit, // keepAliveTime The unit of ,TimeUnit Is an enumerated type 
   BlockingQueue<Runnable> workQueue, // Task queue : Maintaining the Runnable object    When all the core threads are working , The newly added task will be added to the queue to wait for processing , If the queue is full , Then create a new non core thread to execute the task                           
   ThreadFactory threadFactory, // Create a new thread ,Executors.defaultThreadFactory()
   RejectedExecutionHandler handler) // Thread pool saturation strategy 

6419c409ea4f8414a66d5a8b5aaa4443.png

adopt ThreadPoolExecutor.execute(Runnable command) Method to add a task to the thread pool

When a task is added to the thread pool

a197a4589939c590e5bfff3aac9f5193.png

1、 Number of threads not reached corePoolSize, Create a new thread ( Core thread ) Perform tasks
2、 The number of threads has reached corePools, Then move the task to the queue BlockingQueue wait for
3、 If you can't add tasks to BlockingQueue( The queue is full ), Then in non corePool Create a new thread to handle the task ( Be careful , To perform this step, you need to obtain a global lock ).
4、 The queue is full , The number of bus routes has reached maximumPoolSize,(RejectedExecutionHandler) Throw an exception

d476277274f704585f1f980b1a291084.png

f616a018f06e4318741a512fdfc4367d.png

Four kinds of java Implement a good thread pool

CachedThreadPool()

Cacheable thread pool :
There is no limit to the number of threads
If there are idle threads, they will be reused , Create a new thread if there are no idle threads
Make sure programs are created less frequently / Destruction of the thread , Reduce system overhead

FixedThreadPool()

Fixed-length thread pool :
You can control the maximum number of concurrent threads ( Number of threads executing at the same time )
The exceeded thread will wait in the queue

ScheduledThreadPool()

Fixed-length thread pool :
Support regular and periodic task execution .

SingleThreadExecutor()

Singleton thread pool :
There is only one worker thread to perform the task
All tasks are executed in the specified order , That is to follow the rules of the queue

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;




public  class ThreadPoolExecutorTest {
     public  static  void main(String[] args) {
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
        scheduledThreadPool.schedule(new Runnable() {
            public  void run() {
                 System.out.println("delay 3 seconds");
            }
        }, 3, TimeUnit.SECONDS);
    }
}

87faa486b7141789a0e9a8503a17dc95.png

The state of the thread pool

58e58e1379856ae4c9b8fd96c420f7bf.png

6a1ce4c43cc7497a1834e9bed6137294.png

5e1ebfe093b3fad846e590155bbe4ba8.png

3b0fb39b109315acd4e5aa9e03198756.png

Thread pool risk :

Deadlock 、 Insufficient resources 、 Concurrency error 、 Thread leak 、 Request overload

perform execute() Methods and submit() What's the difference between methods ?

  1. execute() Method is used to submit tasks that do not require a return value , Therefore, it is impossible to judge whether the task is successfully executed by the thread pool ;

  2. submit() Method is used to submit tasks that require a return value . The thread pool will return a future Object of type , Through this future Object can determine whether the task is executed successfully , And through future Of get() Method to get the return value ,get() Method blocks the current thread until the task is completed , While using get(long timeout,TimeUnit unit)  Method will block the current thread for a period of time and return to , At this time, it is possible that the task is not finished .

source: //490.github.io/Java Multithreading and concurrency /

Remember to point 「 Fabulous 」 and 「 Looking at 」↓

Love you

原网站

版权声明
本文为[Bug trendsetter]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206091048116843.html