Package COM. starit. open. main; import Java. util. arraylist; import Java. util. list; 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;/***** @ author wenin819 ** callable and future interfaces * callable is similar to runnable interfaces, the classes that implement the callable interface and runnable are all tasks that can be executed by other threads. * There are several differences between callable and runnable: * (1) callable specifies the call () method, while runnable specifies the run () method (). * (2) callable tasks can return values after execution, while runnable tasks cannot return values. * (3) the call () method can throw an exception, while the run () method cannot throw an exception. * (4) run the callable task to get a future object. * future indicates the result of asynchronous calculation. It provides a method to check whether the computation is complete, waiting for the computation to complete and retrieving the computation results. * The future object can be used to understand the task execution status, cancel the task execution, and obtain the task execution result. **/Public class callablethreadsync implements runnable {Private Static final executorservice es = executors. newfixedthreadpool (5); public static class itemthread implements callable <integer> {public int addnum; Public itemthread (INT addnum) {This. addnum = addnum ;}@ overridepublic integer call () {try {thread. sleep (addnum * 1000);} catch (interruptedexception e) {e. printstacktrace ();} return addnum * 2;} public static void main (string [] ARGs) {callablethreadsync test = new callablethreadsync (); long starttime = system. currenttimemillis (); New thread (test, "thread1 "). start (); New thread (test, "thread2 "). start (); long endtime = system. currenttimemillis (); system. out. println ("Main: Time used" + (endtime-starttime)/1000 + "seconds");} public void run () {long starttime = system. currenttimemillis (); List <itemthread> itemthreads = new arraylist <callablethreadsync. itemthread> (3); itemthread = NULL; For (INT I = 0; I <3; I ++) {itemthread = new itemthread (I + 1); itemthreads. add (itemthread) ;}list <future <integer> futurelist = NULL; try {futurelist = es. invokeall (itemthreads);} catch (interruptedexception E1) {e1.printstacktrace ();} integer result = 1; for (Future <integer> future: futurelist) {try {result + = Future. get ();} catch (interruptedexception e) {e. printstacktrace ();} catch (executionexception e) {e. printstacktrace () ;}string infomsg = thread. currentthread (). getname () + ":"; long endtime = system. currenttimemillis (); system. out. println (infomsg + Result + "(time used" + (endtime-starttime)/1000 + "seconds)") ;}@ overrideprotected void finalize () throws throwable {es. shutdownnow (); super. finalize ();}}