Java uses future to get multithreading results in time
The future interface is a part of the Java standard API util. In the concurrent package. The future interface is the implementation of the future pattern of Java threads, which can be used for asynchronous computing.
With future, you can carry out three-stage programming. 1 Start multithreaded task 2 Deal with other matters 3 Collect multithreaded task results. Thus, non blocking task call is realized. A problem encountered on the way is that although the results can be obtained asynchronously, the future results need to judge whether there are results through isdone, or use the get() function to obtain the execution results in a blocking manner. In this way, you can't track the result status of other threads in real time, so you should use get with caution. It's best to use it with isdone.
Here is a better way to obtain the results of any thread in time: use completionservice, which adds a blocking queue to obtain the values in the future, and then do the corresponding processing according to the returned values. The two test cases used by future and completionservice are as follows:
The order of printing operation results and putting future into the list is the same, which is 0, 1, 2:
The following is the scheme of thread processing after first execution:
The running result is the thread that ends first, and the result is processed first:
summary
The above is all about Java using future to obtain thread running results in time. I hope it will be helpful to you. Interested friends can refer to: detailed explanation of Java multithreaded forkjoinpool instance, Java understanding multithreading through ticket selling, implementation code of readwritelock read-write separation of Java multithreading, etc. if you have any questions, you can leave a message at any time. Welcome to exchange and discuss.