Continue concurrent topics~
FutureTask is a bit like Runnable, and can be started through Thread, but FutureTask can return the executed data, and FutureTask's get method supports blocking.
Because: FutureTask can return the executed data, and FutureTask's get method supports blocking these two features, we can use it to pre-load some potentially used resources, and then call get method to get them when needed (if the resources are loaded, return directly; otherwise continue to wait for their load to complete).
Here are two examples:
1. Use FutureTask to preload the data to be used later.
Operation results:
2. Look at Future's API
You can see that the API of Future is still simpler than the simple sense of knowing the name. Get (long, Time Unit) can also support, setting the maximum waiting time, such as an operation that takes too long, can be cancelled.
3. FutureTask simulation, pre-loading function for users to watch e-books Online
When the user watches the current page, the background loads the next page in advance, which can greatly improve the user's experience, without waiting for each page to load, the user will feel that the e-book software is very smooth, haha, the user feels good, is really good.
Output results:
As you can see, besides the process of waiting for network loading data for the first time to view the current page (output: 2001, 1000 is loading time, 1000 is user reading time), the next pages are instantaneous returns (output 1000 is user reading time), there is no need to wait at all.
The code is to explain the application scenario of FutureTask, please do not use it directly in the project.