Java also provides a thread pool that can return values, for example:
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 CallableAndFuture {/** * @param args */public static void main(String[] args) {ExecutorService threadPool = Executors.newSingleThreadExecutor();Future<String> future = threadPool.submit(new Callable<String>(){@Overridepublic String call() throws Exception {Thread.sleep(3000);return "future";}});try {System.out.println("waiting...");System.out.println(future.get());} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}}}
Wait for a while before the future. get () results come out.
Future. get (300, TimeUnit. MILLISECONDS); however, if this is not completed within the specified time, it stops and runs out of a timeout exception.
Note that the generic and call methods in Callable are of the same type as those in Future.
The following example shows how to return multiple Future objects.
// Create the thread pool ExecutorService pool = Executors. newFixedThreadPool (10); // create a CompletionService instance CompletionService <Integer> completionService = new ExecutorCompletionService <Integer> (pool); // submit a task for (int I = 0; I <10; I ++) {final int index = I; completionService. submit (new Callable <Integer> () {@ Overridepublic Integer call () throws Exception {return index ;}}) ;}// obtain the result for (int I = 0; I <10; I ++) {try {Future <Integer> future2 = completionService. take (); System. out. println (future2.get ();} catch (InterruptedException e) {e. printStackTrace ();} catch (ExecutionException e) {e. printStackTrace ();}}}
Confused: I don't know where to use it. I have never encountered this situation in business requirements.