1 ImportJava.util.Random;2 Importjava.util.concurrent.Callable;3 ImportJava.util.concurrent.CompletionService;4 Importjava.util.concurrent.ExecutionException;5 ImportJava.util.concurrent.ExecutorCompletionService;6 ImportJava.util.concurrent.ExecutorService;7 Importjava.util.concurrent.Executors;8 Importjava.util.concurrent.Future;9 Ten /** One * Application of callable and future A * The result type obtained by the future must be the same as the result type returned by callable, which is implemented by generics. - * Callable to be submitted using the Executorservice Submit method, the returned future object can cancel the task. - * Completionservice is used to submit a set of callable tasks whose take method returns the corresponding future object for a completed callable task. the * @authorlitaiqing - * - */ - Public classCallableandfuture { + - Public Static voidMain (string[] args) { + AExecutorservice ThreadPool =executors.newsinglethreadexecutor (); atfuture<string> future = - //With submit when returning results -Threadpool.submit (NewCallable<string>(){ - @Override - PublicString Call ()throwsException { - return"Hello"; in } - to }); + -System.out.println ("Wait for results"); the Try { *System.out.println ("Get Results" +future.get ()); $}Catch(interruptedexception e) {Panax Notoginseng e.printstacktrace (); -}Catch(executionexception e) { the e.printstacktrace (); + } A theExecutorservice threadPool2 = Executors.newfixedthreadpool (10); +Completionservice<integer> Completionservice =NewExecutorcompletionservice<integer>(threadPool2); - for(inti = 1; I < 10; i++){ $ Final intSeq =i; $Completionservice.submit (NewCallable<integer>(){ - @Override - PublicInteger Call ()throwsException { theThread.Sleep (NewRandom (). Nextint (5000)); - returnseq;Wuyi } the - }); Wu } - About for(inti = 0; I < 10; i++){ $ Try { - System.out.println (Completionservice.take (). get ()); -}Catch(interruptedexception e) { - e.printstacktrace (); A}Catch(executionexception e) { + e.printstacktrace (); the }; - } $ the } the the}
Application of 10.Callable and future