Thread pool concept 2

Thread pool class diagram

ExecutorService: It is the most basic interface of a thread pool, which provides the basic methods of submitting tasks and closing the thread pool.

ScheduledExecutorService: Extended interface, adding task scheduling function to the basic thread pool function, which can be used to execute tasks regularly.

thread pool status 

Commonly used methods in the thread pool

 The timeout here is for all tasks, not for a single task. If it times out, all unfinished tasks will be canceled and a timeout exception will be thrown. It is equivalent to saving the execution status of each future with a list collection. When calling the future.get() method to get the value, compare it with the set timeout to see if it times out.

Task scheduling thread pool

Sometimes it is desired to delay the execution of the task (executed in a few seconds), and to execute the task repeatedly (executed once in a few seconds).

ScheduledThreadPoolExecutor-delayed execution

Here the tasks are not executed serially because here the number of core threads is exactly 2. If it is 1 here, it is executed serially like timer. A delay or exception in the previous task will not affect the subsequent tasks.

 ScheduledThreadPoolExecutor - periodic execution

scheduleAtFixedRate(task,initialDelay,period,timeUnit);

task: is the task to be executed.

 initialDelay: The initial delay, such as waiting for one second after printing start before executing the task.

period: The task of the next cycle will be executed every second. It takes 2 seconds to execute the task each time, and the setting here is to cycle the next time every second. So wait two seconds before looping the next time.

scheduleWithFixedDelay(task,initialDelay,delay,timeUnit);

The difference from scheduleAtFixedRate is that this task needs to wait for the execution of the previous cycle to complete before delaying the next cycle. So here we have to wait for 3s.

 Exception handling in thread pool

The thread pool will not actively throw exceptions. Generally, there are two processing methods.

1. Active try catch.

 2. Call the get method by implementing the callable interface. If an exception occurs, the exception information will be returned.

Guess you like

Origin blog.csdn.net/weixin_54401017/article/details/126968946