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