Demo1: Gets the return value of a thread using Futuretask and callable. You can do other things before you get the return value, block at Future.get (), or call
The Get (long timeout, Timeunit unit) method sets the exception after waiting for a long time if no return value has been thrown.
Package Com.lipeng;import Java.util.concurrent.callable;import Java.util.concurrent.futuretask;public class FutureAndCallable1 {/** * uses 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 the Thread.//futuretask implementation of the callable interface, can get the thread return value by Get futuretask<string> Futuretask=new futuretask<string> (New callable<string> () {@Overridepublic String call () throws Exception { Thread.Sleep (+); return "Hello";}}); New Thread (Futuretask). Start (); SYSTEM.OUT.PRINTLN ("Thread start ... ");//dosomethingsystem.out.println (Futuretask.get ());}}
D Emo2: 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> () {@Overridepublic String call () Throws Exception {thread.sleep; return "Hello";}}); System.out.println ("--------"); System.out.println (Future.get ());}}
3 Execute multiple call methods simultaneously, return multiple return values, who first executes who first returns
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 void main (string[] args) throws Exception {Executorse Rvice 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> () {@Overridepublic Integer call () throws Exception {int time=new Random (). Nextint (5000); Thread.Sleep (time); return j;});} System.out.println ("---------------------------"); for (int i=0;i<10;i++) {int a=cs.take (). get (); System.out.println (a);} Executorservice.shutdown ();}}
Java Multi-Threading and concurrency Applications-(8)-callable and future