Callable<> and runable are similar and are used for concurrent execution of Java.
The only difference is that the return of the runable run method is void, and the call method of callable has a return value .
The type returned by the call method is the type specified when implementing the Callable<?> generic interface, or a compilation error occurs.
So, how do you get the return value of the call method? -- by executing callable, you can return a future object by invoking the Get method of the future object to get the return value of the call method.
In summary, you take callable as a return value of runable on the line, but callable is the call,runable is run.
Here is the demo code:
1 Importjava.util.ArrayList;2 Importjava.util.concurrent.Callable;3 Importjava.util.concurrent.ExecutionException;4 ImportJava.util.concurrent.ExecutorService;5 Importjava.util.concurrent.Executors;6 Importjava.util.concurrent.Future;7 8 9 Public classcallabletest{Ten Public Static voidMain (string[] args) { OneExecutorservice executorservice=//Create a thread pool A Executors.newcachedthreadpool (); -Arraylist<future<string>> list= - NewArraylist<future<string>>(); the for(inti = 0; I < 10; i++) { -List.add (Executorservice//submit callable to thread pool execution via the Submit method -. Submit (NewTaskwithresult ())); - } + for(future<string>future:list) { - Try { +System.out.println (Future.get ());//get call return value by Get method A}Catch(interruptedexception e) { at e.printstacktrace (); -}Catch(executionexception e) { - e.printstacktrace (); - } - } - } in - to Static classTaskwithresultImplementsCallable<string>{ + Private Static intTasknum=0; - Private intTaskid=Tasknum; the PublicTaskwithresult () { *tasknum++; $ }Panax Notoginseng - @Override the PublicString Call ()throwsException { + Try { AThread.Sleep ( This. taskid*1000);//The time difference I make makes it more intuitive to show the similarity between the call and the Run method. the}Catch(interruptedexception e) { + e.printstacktrace (); - } $ return"Result of Taskwithresult:" + This. taskId; $ } - - } the -}
Operation 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
The above results are printed one line at a second, which means that call and run are similar.
Use of Java callable