Callable and Future in java threads
Future is an interface,FutureThe 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. OnlyGetMethod to retrieve results. If necessary, this method can be blocked before computation is complete. CancelCancelMethod. Other methods are provided to determine whether the task is completed normally or canceled. Once the computation is completed, the computation cannot be canceled. If you useFutureBut does not provide available results, you can declareFuture Form type, and returnNullAs the result of the basic task. Instance code:
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; public class FutureDemo {public static void main (String [] args) throws Exception, ExecutionException {ExecutorService threadPool = Executors. newFixedThreadPool (3); Future
Future = threadPool. submit (new Callable
() {@ Overridepublic String call () throws Exception {Thread. sleep (10000); return "hello" ;}}); System. out. println ("waiting for results"); System. out. println ("Result:" + future. get ());}}
We know that one of the methods for executing tasks in ExecutorService is execute (), but it does not return the value. The return value of the subibd () method is Future, and the Future method has a get method, it returns the real result. This is to execute a task. If you want to execute a group of tasks, java also provides an interface CompletionService, which has an implementation class ExecutorCompletionService,
Sample Code:
Public class FutureDemo {public static void main (String [] args) throws Exception, ExecutionException {ExecutorService threadPool = Executors. newFixedThreadPool (3); ExecutorCompletionService
Ecs = new ExecutorCompletionService
(ThreadPool); for (int I = 0; I <10; I ++) {final int seq = I; ecs. submit (new Callable
() {@ Overridepublic Integer call () throws Exception {Thread. sleep (new Random (). nextInt (5000); return seq ;}});} System. out. println ("result -----------"); for (int I = 0; I <10; I ++) {Future
Take = ecs. take (); System. out. println ("the result is:" + take. get ());}}}
Print result:
Result ----------- result: 0 result: 3 result: 2 result: 5 result: 6 result: 1 result: 4. The result is 7. The result is 8. The result is 9.