When creating a multithreaded programming, we often implement the Runnable interface, runnable no return value, to get the return value, JAVA5 provides a new interface callable, can get the return value of the thread, but to get the return value of the thread, you need to be aware that Our method is asynchronous, and when we get the return value, the thread task does not necessarily have a return value, so we need to determine if the thread is finished before we can go to the value.
Test code
Package com.wuwii.test;import java.util.concurrent.*;/** * @authorZhang Kai * @version1.0* @since <pre>2017/10/31 11:17</pre> */ Public classTest {Private Static FinalInteger Sleep_mills = the;Private Static FinalInteger Run_sleep_mills = +;Private intAfterseconds = Sleep_mills/run_sleep_mills;//thread pool (depending on the number of cores of the machine) Private FinalExecutorservice Fixedthreadpool = executors.Newfixedthreadpool(Runtime.GetRuntime().availableprocessors());Private void testcallable()throwsinterruptedexception {future<string> future =NULL;Try{/*** When creating multi-thread programming, we often implement the Runnable interface, runnable no return value, to get the return value, JAVA5 provides a new interface callable ** Callable need to implement the call () method, not the run () method, the type of the return value is specified by the type parameter of the callable,* Callable can only be performed by Executorservice.submit () and will return a future object after normal completion. */Future = Fixedthreadpool.Submit((), {Thread.Sleep(Sleep_mills);return "The thread returns value."; }); }Catch(Exception e) {e.Printstacktrace(); }if(Future = =NULL)return; for(;;) {/*** Before acquiring a future object, you can use the Isdone () method to detect if the future is complete, and you can call the Get () method to get the future value after completion .* If you call the Get () method directly, the Get () method will block to the end of the thread and is wasteful. */ if(future.IsDone()) {Try{System. out.println(future.Get()); Break; }Catch(Interruptedexception | Executionexception e) {e.Printstacktrace(); } }Else{System. out.println("after"+ afterseconds--+"Seconds,get the Future Returns value."); Thread.Sleep( +); } } } Public Static void Main(string[] args)throwsinterruptedexception {New Test().testcallable(); }}
Operation Result:
After 3 seconds,get the future returns value.After 2 seconds,get the future returns value.After 1 seconds,get the future returns value.The thread returns value.
Summarize:
- The thread that needs the return value uses the callable interface to implement the Call method;
- Before acquiring a future object, you can use the Isdone () method to detect if the future is complete, and you can call the Get () method to get the future value after completion, and if you call the Get () method directly, the get () method blocks to the end of the thread.
Using threads with return values in Java