Two methods based on scheduledexecutorservice (detailed explanation)

In development, it is often encountered that another thread executes other code, which is implemented with the Java scheduled task interface scheduledexecutorservice.

Scheduledexecutorservice is a scheduled task class designed based on the thread pool. Each scheduled task will be assigned to a thread in the thread pool for execution, that is, tasks are executed concurrently and do not affect each other.

Note that only when the scheduled task comes, the scheduled executorservice will actually start a thread, and the scheduled executorservice is in the polling task state the rest of the time.

1. Scheduleatfixedrate method

example:

Operation results:

It can be seen that after 2S, the sub thread starts to execute, and polling is executed every 3S.

2. Schedulewithfixeddelay method

example:

Operation results:

3. Two differences

Each execution time of scheduleatfixedrate is a time interval pushed back from the start of the last task, that is, each execution time is initialdelay, initialdelay + period, initialdelay + 2 * period.....

Each execution time of schedulewithfixeddelay is a time interval pushed back from the end of the last task, that is, each execution time is: initialdelay, initialdelay + executetime + delay, initialdelay + 2 * executetime + 2 * delay.....

It can be seen that scheduleatfixedrate schedules tasks based on fixed time intervals. Schedulewithfixeddelay schedules tasks based on non fixed time intervals depending on the length of time each task is executed.

The above two methods (detailed explanation) based on scheduled executorservice are all the contents shared by Xiaobian. I hope it can give you a reference and support more programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>