Application example code of Java Concurrent Programming callable and future

This paper mainly explores the use of Java Concurrent Programming, label and future, and shares the relevant example code. The details are as follows.

We all know that there are two ways to implement multithreading, one is to inherit thread and the other is to implement runnable. However, both methods have a defect that they cannot obtain the returned results after the task is completed. To get the return result, you have to use callable. Callable tasks can have return values, but you can't get the return values directly from callable tasks; To get the return value of the callabel task, you need to use future. Therefore, callable tasks and future mode are usually used together.

Imagine a scenario: you need a post list interface. In addition to returning the post list, you also need to return the likes list and comments list of each post. It is calculated by 10 posts on a page. This interface needs to access the database 21 times. Access to the database once is calculated as 100ms, 21 times, and the cumulative time is 2.1S. This response time may not be satisfactory. What shall I do? Asynchronous transformation interface.

After finding out the post list, iterate the post list, start 10 threads in the loop to obtain the praise list of each post, and start another 10 threads to obtain the comment list of each post concurrently. After such transformation, the response time of the interface is greatly shortened, at 200ms. At this time, callabel should be combined with future.

summary

The above is all about the application example code of Java Concurrent Programming callable and future. I hope it will be helpful to you. Interested friends can continue to refer to other related topics on this site. If there are deficiencies, please leave a message to point out. Thank you for your support!

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