Callable such a task can return results, and the returned results can be taken from the future.
The result type obtained by >future and the result type returned by callable must be the same, which is achieved by generics.
>completionservice is used to submit a set of callable tasks whose take method returns the corresponding future object for a completed callable task.
Like I planted a few pieces of wheat at the same time, and then waited for the harvest. When the harvest is ripe, it is the first to reap the wheat.
future<string> future = Threadpool.submit (new callable< String> () {@Override public String Call () throws Exception {Threa D.sleep ( 2000 return "Hello" ; } }); SYSTEM.OUT.PRINTLN ( wait result try {System.out.println ( "Get results: "+future.get ()); catch (Exception e) {E.printstacktra CE (); }
This type of hair is the future to actively ask callable whether it produces results
>completionservice is used to submit a set of callable tasks whose take method returns the corresponding future object for a completed callable task.
Executorservice executor = Executors.newfixedthreadpool (10); Completionservice<Integer> Completionservice =NewExecutorcompletionservice<>(executor); for(inti = 0;i<10;i++){ Final intSeq =i; Completionservice.submit (NewCallable<integer>() {@Override PublicInteger Call ()throwsException {thread.sleep (NewRandom (). Nextint (5000)); returnseq; } }); } for(inti = 0;i<10;i++) {//waiting to get results Try{System.out.println (Completionservice.take (). get ()); } Catch(Exception e) {e.printstacktrace (); }; }
Java Multi-Threading and Concurrency Library Advanced application-callable and future application