One, descriptive narrative
? When programming in multi-threaded. There is a need for people to be able to get the combination of the future and the callable in a way that I would like to have when the threads I open end up with the data returned from each thread at the same time and then do a unified process.
Some people will say, I can use synchronization to complete this demand ah, ordinary circumstances can indeed. But in a special case it is not:
Imagine that you turned on multiple threads to compute some data synchronously, but as we all know, threads are competing for resources, that is to say. When you turn on multiple threads to synchronize the calculation data. In fact, the order of calculation between threads is not null, of course, unless you have a lot of trouble to deal with is not possible. In such a case. The combination of future and callable is the choice of the two.
?
Second, sample
The examples of these two classes are in fact very easy to see if they can find their niche in practical use. On the 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 Feturecallabletest {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 <, 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 (); }}
Explanation and use of Java multithreading future and callable class