Using threads with return values in Java

Source: Internet
Author: User

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:
    1. The thread that needs the return value uses the callable interface to implement the Call method;
    2. 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.