FutureTask

Asynchronous, never synchronous, parallel, never serial

1. Future

A future represents the result of an asynchronous calculation. Future provides methods to check whether the calculation is completed, wait for the calculation to be completed, and obtain the calculation results. Only after the calculation is completed can the get method be used to retrieve the results, otherwise it will be blocked until the calculation is completed. The cancel method can cancel execution. In addition, it also provides a method to check whether the task is completed normally or cancelled. Once the calculation is completed, the calculation cannot be cancelled.

Simple usage:

Futuretask class is the implementation of future. It also implements runnable, so it can also be executed by the executor. For example, the above code can be rewritten as follows:

2. FutureTask

A futuretask can be used to wrap a callable or runnable object. Because futuretask implements the runnable interface, a futuretask can be submitted to an executor for execution.

3. Examples

output

In the actual development process, the long-time and parallel operations are encapsulated into a futuretask (for example, some data are obtained by calling Dubbo service, some data need to be read from cache, and some data need complex calculation)

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
分享
二维码
< <上一篇
下一篇>>