1. Concept
Future represents the result of an asynchronous task that may not have been completed. Callback can be added to this result to perform corresponding operations after the task execution succeeds or fails.
2. Future interface
The Future interface defines five main interface methods. RunnableFuture and ScheduleFuture inherit this interface, and CompleteFuture and ForkJoinTask inherit this interface.
3. Examples
package test; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class CallableFutureTest { public static void main(String[] args) { long startTime = System.currentTimeMillis(); Callable<Integer> calculateCallable = new Callable<Integer>() { @Override public Integer call() throws Exception { // TODO Auto-generated method stub Thread.sleep(2000); //Simulation time consuming int result = 1+2; return result; } }; FutureTask<Integer> calculateFutureTask = new FutureTask<>(calculateCallable); Thread t1 = new Thread(calculateFutureTask); t1.start(); //Now join Thread to run a time-consuming service that simulates remote calls and relies on its calculation results (such as a network calculator) try { //Simulate time-consuming tasks, the main thread does its own thing, reflecting the advantages of multi-threading Thread.sleep(3000); int a = 3+5; Integer result = calculateFutureTask.get(); System.out.println("result = "+(a+result));//Simulate the running result of the main thread relying on the sub-thread long endTime = System.currentTimeMillis(); System.out.println("time = "+(endTime-startTime)+"ms"); } catch (InterruptedException | ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
As you can see from the above, the time taken above is about 3s. In fact, it is mainly the time spent by the main thread sleep(3000). If we do not use Future and rely on the results of the thread, the time we may need may be 5s (sub-thread 2s+ main thread 3s).
The above is how Future obtains thread results in Java. It can be said that Future is more flexible in processing threads. The mechanism is roughly that when one thread is running, another thread runs at the same time. If you are interested, you can learn more after class.