Demo1: Gets the return value of a thread using Futuretask and callable. You can do something else before you get the return value, block when Future.get (), or you can call the
The Get (long timeout, Timeunit unit) method sets the exception to throw if no return value has been returned after a long wait.
Package Com.lipeng;
Import java.util.concurrent.Callable;
Import Java.util.concurrent.FutureTask;
public class FutureAndCallable1 {
/**
* using Futuretask and callable
* @param args/public
static void Main (string[] args) throws Exception {
//futuretask implements the Runnalbe interface, so it can be used to construct thread.
Futuretask implements the callable interface, which can fetch the thread return value
futuretask<string> futuretask=new futuretask<string> ( New Callable<string> () {
@Override public
String call () throws Exception {
thread.sleep (3000);
return "Hello";
}
);
New Thread (Futuretask). Start ();
System.out.println ("thread begins ...") ");
DoSomething
System.out.println (Futuretask.get ());
}
Demo2: Using Executorservice's Submit (callable C) method
Package Com.lipeng;
Import java.util.concurrent.Callable;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.Future;
public class FutureAndCallable2 {
/**
* Using Executorservice's submit (callable C) method
* @param args
* * public static void Main (string[] args) throws Exception {
executorservice executorservice= Executors.newfixedthreadpool (3);
Future<string> Future=executorservice.submit (New callable<string> () {
@Override
public String call () throws Exception {
thread.sleep (3000);
return "Hello";
}
);
System.out.println ("--------");
System.out.println (Future.get ());
}
3 Execute multiple call methods at the same time, returning multiple return values, who performs first and who returns first
Package Com.lipeng;
Import Java.util.Random;
Import java.util.concurrent.Callable;
Import Java.util.concurrent.CompletionService;
Import Java.util.concurrent.ExecutorCompletionService;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors; public class FutureAndCallable2 {/** * using Executorservice's submit (callable C) method * @param args/public static voi
D main (string[] args) throws Exception {Executorservice Executorservice=executors.newfixedthreadpool (3);
Completionservice<integer> cs=new Executorcompletionservice (executorservice);
for (int i=0;i<10;i++) {final int j=i; Cs.submit (New callable<integer> () {@Override public Integer call () throws Exception {int time=new Ran
Dom (). Nextint (5000);
Thread.Sleep (time);
Return J;
}
});
} System.out.println ("---------------------------");
for (int i=0;i<10;i++) {int a=cs.take ().
System.out.println (a); } executorseRvice.shutdown ();
}
}