Multithreading 1 - Thread Pool

1. Processing flow

(1) If the number of currently running threads is less than corePoolSize, a new thread is created to execute the task.

(2) If the number of running threads is not less than corePoolSize, add the task to the BlockingQueue.

(3) If the BlockingQueue queue is full, a new thread is created to execute the task.

(4) If the creation of new threads will cause the total number of threads to exceed the maximumPoolSize, the task will be rejected.

2. Worker thread:

When the thread pool creates a thread, it will encapsulate the thread into a worker thread Worker. After the worker finishes executing the task, it will also cyclically obtain the tasks in the work queue for execution.

3. Thread execution tasks in the thread pool are divided into two cases, as follows.

(1) When a thread is created in the execute(Runnable command) method, the thread will execute the current task.

(2) After the thread finishes executing the current task, it will repeatedly obtain tasks from the BlockingQueue to execute.

 

Call the thread pool's prestartAllCoreThread() method to create and start all basic threads in advance.

4. Create a thread pool:

(1) corePoolSize: the basic number of threads in the thread pool

(2) workQueue: task queue, FIFO first in first out.

(3) maximumPoolSize: The maximum number of thread pools. If the number of threads is more than corePoolSize and the workQueue is full, new threads will be created, but the total number will not exceed maximumPoolSize.

(4) ThreadFactory: used to customize the creation of threads, which is convenient to name the threads.

(5) RejectedExecutionHandler: Saturation strategy, when the queue and thread pool are full, indicating that the thread pool is saturated, a strategy must be adopted to process newly submitted tasks.

There are four kinds:

①AbortPolicy: throw an exception directly

②CallerRunsPolicy: Only use the thread where the caller is located to run the task.

③DiscardOldestPolicy: Discard the latest task in the queue and execute the current task.

④DiscardPolicy: If it is not processed, discard it.

It is also possible to customize strategies, such as logging or persisting tasks.

(6) keepAliveTime: thread activity retention time, the time that the worker thread of the thread pool will remain alive after it is idle. TimeUnit: The unit of thread activity retention time.

5. Submit tasks to the thread pool:

(1) The execute() method submits a task without a return value

(2) The submit() method will return an object of type future

6. Close the thread pool

(1) The shutdown method will wait for the current task to complete.

(2) The shutdownNow method will interrupt the thread that is executing the task

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325441525&siteId=291194637