One, descriptive narration
When programming in multithreading. You may encounter a requirement that I want to get the data returned from each thread at the end of the thread that I started, and then do the same, and in this demand, the combination of future and callable is very useful.
Some people will say, I can use synchronization to complete this demand ah, in general, can indeed. But in a special case it doesn't:
Imagine that you've opened multiple threads to compute some data synchronously, but as you know, threads are competing for resources, that is to say. You turn on multiple threads to synchronize the data. In fact, the order of calculation between threads is not empty, of course, unless you have a lot of trouble to deal with it is not possible. In such a case. The combination of future and callable is the second choice.
Second, the sample
The examples of these two classes are actually very easy to use, mainly to see if they can find their application in practice. Code on:
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 (). Getn
Ame ());
return ++count;
}
});
int f = future.get ();
sum = f;
System.out.println ("Future is" + f);
} System.out.println ("sum is" + sum);
Service.shutdownnow (); }
}