1. Describe and narrative
When programming under multithreading. You may encounter a need, that is, when the threads I open end, I want to obtain the data returned in each thread at the same time and then perform unified processing. Under this requirement, the combination of Future and Callable comes in great use.
Some people may also say that I can use synchronization to complete this requirement, but it is indeed possible in ordinary cases. But in a special case, it won't work:
Imagine that you have enabled multiple threads to synchronously calculate some data, but everyone knows that threads will compete for resources, that is. When you enable multiple threads to synchronize the calculation of data. In fact, the calculation order between threads cannot be null, of course, it is not impossible to deal with it unless you do not make a big mistake. In such a case. The combination of Future and Callable is the best choice.
2. Sample examples
The examples of these two categories are actually very easy, mainly depending on whether you can find their use in actual use. On code:
package test; 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 FeatureCallableTest { private static ExecutorService service = Executors.newFixedThreadPool(100); private static int count = 1; public static void main(String[] args) throws InterruptedException, ExecutionException { int sum = 0; for(int i = 0; i < 100; i++) { Future<Integer> future = service.submit(new Callable<Integer>(){ @Override public Integer call() throws Exception { System.out.println(Thread.currentThread().getName()); return ++count; } }); int f = future.get(); sum += f; System.out.println("future is " + f); } System.out.println("sum is " + sum); service.shutdownNow(); } }