Turn from: JAVA notes callable and Futuretask: Multithreading with return values
The commonly used thread class has no return value after the Run method executes, and a third-party dump is required to implement the return value to the main thread after the child thread completes the task. The callable interface provides a multithreaded implementation method with return values. Here is a simple landlord, Overwatch Hachang example to show the use of this interface.
Permanent class:
The working class implements the callable interface, which returns an integer value after the thread has finished running.
Packagecom.lk.c;Importjava.util.concurrent.Callable; Public classChanggongImplementsCallable<integer>{//generics restrict the return value type of an overriding method Private intHours=12; Private intamount; @Override PublicInteger Call ()throwsException { while(hours>0) {System.out.println ("I ' m working ..."); Amount++; Hours--; Thread.Sleep (1000); } returnamount; }}
Landlord: Master Process
Supervisor: Futuretask
Packagecom.lk.c;Importjava.util.concurrent.ExecutionException;ImportJava.util.concurrent.FutureTask; Public classDizhu { Public Static voidMain (String args[]) {Changgong worker=NewChanggong (); Futuretask<Integer> Jiangong =NewFuturetask<integer>(worker); NewThread (Jiangong). Start (); while(!Jiangong.isdone ()) { Try{System.out.println ("The View from the ..."); Thread.Sleep (1000); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } intamount; Try{Amount=Jiangong.get (); System.out.println ("Finished the work, turned in" +amount); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(executionexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}
I ' m working ... See if the permanent has been finished ... I' m working ... See if the permanent has been finished ... See if the permanent has been finished ... I' m working ... See if the permanent has been finished ... I' m working ... I ' m working ... See if the permanent has been finished ... I' m working ... See if the permanent has been finished ... See if the permanent has been finished ... I' m working ... I ' m working ... See if the permanent has been finished ... See if the permanent has been finished ... I' m working ... I ' m working ... See if the permanent has been finished ... I' m working ... See if the permanent has been finished ... See if the permanent has been finished ... I' m working ... See if the permanent has been finished ... Finished the work and handed in
callable--creating a thread with a return value