Concurrency: Callabel interface

Source: Internet
Author: User

The callable interface is a generic with a type parameter, and its call () method returns a generic type and can throw an exception. It must be called using the Executorservice#submit () method.

1  Public classTaskwithresultImplementsCallable<string> {2 3     Private intID;4 5      PublicTaskwithresult (intID) {6          This. id=ID;7     }8 9 @OverrideTen      PublicString Call ()throwsException { One         //TODO auto-generated Method Stub A         return"Result of Taskwithresult:" +ID; -     } -  the}

1  Public classCallabledemo {2      Public Static voidMain (string[] args) {3         //TODO auto-generated Method Stub4Executorservice exec =Executors.newcachedthreadpool ();5arraylist<future<string>> results =NewArraylist<future<string>>();6          for(inti = 0; I < 10; i++)7Results.add (Exec.submit (NewTaskwithresult (i)));8          for(future<string>fs:results)9             Try {Ten System.out.println (Fs.get ()); One}Catch(interruptedexception e) { A                 //TODO auto-generated Catch block - e.printstacktrace (); -}Catch(executionexception e) { the                 //TODO auto-generated Catch block - e.printstacktrace (); -}finally{ - Exec.shutdown (); +             } -     } +}

The Submit () method returns a future object where the future object Callable#call the return value of the () parameter, and calls Future#get () to get the return result of call (). Use Future#isdone () to determine if the thread is executing, and if Future#get () is called directly, get () will block until the result is ready.

Execution Result:

Result of taskwithresult:0
Result of Taskwithresult:1
Result of Taskwithresult:2
Result of Taskwithresult:3
Result of Taskwithresult:4
Result of Taskwithresult:5
Result of Taskwithresult:6
Result of Taskwithresult:7
Result of Taskwithresult:8
Result of Taskwithresult:9

Concurrency: Callabel interface

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.