Java also provides a thread pool that can return a value, as shown in the following example:
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 Callableandfuture {
/**
* @param args
*
/public static void main (string[] args) {
Executorservice ThreadPool = Executors.newsinglethreadexecutor ();
future<string> Future = threadpool.submit (new callable<string> () {
@Override public
String Call () throws Exception {
thread.sleep (3000);
Return "Future";
}
);
try {
System.out.println ("Waiting ...");
System.out.println (Future.get ());
} catch (Interruptedexception e) {
e.printstacktrace ();
} catch (Executionexception e) {
E.printstacktrace ();}}
Future.get () before the results come out, wait a while
Future.get (timeunit.milliseconds); However, if this is not done within the specified time, stop and run out of timeout exceptions
There is also the need to note that the generics and call methods in callable are the same type as the future generic type.
The following example is that you can return multiple future objects
Create a thread pool
executorservice pool = Executors.newfixedthreadpool (a);
Create Completionservice instance
completionservice<integer> completionservice = new executorcompletionservice< Integer> (pool);
Commit task for
(int i = 0;i < i++) {
final int index = i;
Completionservice.submit (New callable<integer> () {
@Override public
Integer call () throws Exception { return
Index;}}
);
Get results for
(int i = 0;i<10;i++) {
try {
future<integer> future2 = Completionservice.take ();
System.out.println (Future2.get ());
} catch (Interruptedexception e) {
e.printstacktrace ();
} catch (Executionexception e) {
E.printstacktrace ();}}
Confused: don't know where to use, business needs have not encountered this situation