ImportJava.util.Random;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.CompletionService;ImportJava.util.concurrent.ExecutorCompletionService;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future;/*** Callable Future completionservice Test * * The future results type and results of callable return * * Callable required Executorservice submit using Submit method * * Completionservice is used to submit a set of callable, where the Take method returns the completed callable task * *@authorDuwenlei **/ Public classCallablefuturetest {Private Static voidTestcallable ()throwsException {executorservice service=Executors.newsinglethreadexecutor (); Future<String> future = Service.submit (NewCallable<string>() {@Override PublicString Call ()throwsException {thread.sleep (5000);//stop 5 Seconds to return return"Hello"; } }); System.out.println ("Wait for results"); System.out.println ("Get results:" +future.get ()); //System.out.println ("Get Results:" +future.get (1, timeunit.seconds));Service.shutdown (); } Private Static voidTestcompletionservice ()throwsexception{Executorservice Executor= Executors.newfixedthreadpool (3); Completionservice<Integer> Service =Newexecutorcompletionservice<integer> (executor);//need a thread pool for(inti = 1; I <= 10; i++) { Final intSeq =i; Service.submit (NewCallable<integer>() {@Override PublicInteger Call ()throwsException {thread.sleep (NewRandom (). Nextint (5000));//rest time, not sure. returnseq; } }); } for(inti = 1; I <= 10; i++) {System.out.println (Service.take (). get ()); } executor.shutdown (); } Public Static voidMain (string[] args) {Try{testcallable (); } Catch(Exception e) {e.printstacktrace (); } Try{testcompletionservice (); } Catch(Exception e) {e.printstacktrace (); } }}
Callable and future in the Java thread pool