Java uses Callable and Future to return the results of thread execution

Source: Internet
Author: User

Java uses Callable and Future to return the results of thread execution

We may need to return the result of a thread execution under some special requirements. The Callable and Futrue functions provided in java 1.5 can help you achieve this! Read the code without explanation

 

Package cn.kge.com; import java. util. concurrent. callable; import java. util. concurrent. executionException; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. future; public class Demo2 {public static void main (String [] args) {ExecutorService threadPool = Executors. newSingleThreadExecutor (); Future

 
  
Future = threadPool. submit (new Callable

  
   
() {Public String call () {String str = "hello"; try {Thread. sleep (2000);} catch (InterruptedException e) {e. printStackTrace ();} return str + "world" ;}}); try {System. out. println ("execution result:" + future. get ();} catch (InterruptedException e) {e. printStackTrace ();} catch (ExecutionException e) {e. printStackTrace ();}}}

  

 

Execution result: helloworld

 

 

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.