In the actual development process, we often need to wait for a batch of threads to return the results before continuing execution. "Thread Waiting for--countdownlatch use" we introduced the use of Countdownlatch, by using Countdownlatch, you can implement thread waiting.
JDK 1.8 implements a better way to implement thread wait and get thread return value, that is the callable interface, let's take a look at the specific code.
PackageCom.coshaho.learn;ImportJava.util.Random;Importjava.util.concurrent.Callable;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;Importjava.util.concurrent.Future;ImportOrg.apache.kafka.common.group.Time; Public classcallablelearn{ Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {LongStart =System.currenttimemillis (); Mycallabletask Task1=NewMycallabletask (); Mycallabletask Task2=NewMycallabletask (); Mycallabletask Task3=NewMycallabletask (); //you can get the return value using the thread Submit methodFuture<string> Future1 =Fixed_threadpool.submit (TASK1); Future<String> Future2 =Fixed_threadpool.submit (TASK2); Future<String> future3 =Fixed_threadpool.submit (TASK3); LongEnd =System.currenttimemillis (); //Task commit does not blockSYSTEM.OUT.PRINTLN ("Submit Task Cost" + (End-start) + "Ms."); System.out.println ("Task1:" +future1.get ()); System.out.println ("Task2:" +future2.get ()); System.out.println ("TASK3:" +future3.get ()); //Future.get method waits for a thread to return a valueSYSTEM.OUT.PRINTLN ("Get Task return value cost" + (System.currenttimemillis ()-end) + "Ms."); } //a thread pool of size 3 Public Final StaticExecutorservice Fixed_threadpool = Executors.newfixedthreadpool (3); Public Static classMycallabletaskImplementsCallable<string> { //sleep I seconds and return information@Override PublicString Call ()throwsException {random random=NewRandom (); inti = Random.nextint (10) * 1000; Time.sleep (i); return"Sleep" + i + "Ms."; } }}
Results
Submit task cost 3ms.
Task1:sleep 5000ms.
Task2:sleep 8000ms.
Task3:sleep 8000ms.
Get task return value cost 8659ms.
Three key points
1. Thread needs to implement callable interface
2. The thread pool submits the task using the Submit method, which can get the return value of the future
3. When using the Future.get method, the current thread is blocked, waiting for the task to return a value
Java Callable interface--a thread with a return value