Common thread classes do not return values after the run method is executed. To return values to the main thread after the sub-thread completes the task, a third-party transfer is required. The callable interface provides a multi-threaded implementation method with a returned value. The following is an example of a simple landlord, supervisor, and chief engineer interface.
Long Job class:
The long job class implements the callable interface. After the thread finishes running, an integer value is returned.
Import Java. util. Concurrent. callable;
Public ClassChanggongImplementsCallable <integer> {
Private Int Hours = 12;
Private Int Amount;
@ Override
Public Integer call () Throws Exception {
While (Hours> 0 ){
System. Out. println ("I'm working ......");
Amount ++;
Hours --;
Thread. Sleep (1000 );
}
Return Amount;
}
}
Landlord: Main Process
Supervisor: futuretask
Import Java. util. Concurrent. executionexception;
Import Java. util. Concurrent. futuretask;
Public Class Dizhu {
Public Static Void Main (string ARGs []) {
Changgong worker = New Changgong ();
Futuretask <integer> Jiangong = New Futuretask <integer> (worker );
New Thread (Jiangong). Start ();
While (! Jiangong. isdone ()){
Try {
System. Out. println ("do you want to finish the long job ...");
Thread. Sleep (1000 );
} Catch (Interruptedexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
Int Amount;
Try {
Amount = Jiangong. Get ();
System. Out. println ("finished, handed in" + amount );
} Catch (Interruptedexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (Executionexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
}
Running result:
Are the workers finished...
I'm working ......
Are the workers finished...
I'm working ......
Are the workers finished...
I'm working ......
Are the workers finished...
I'm working ......
Are the workers finished...
I'm working ......
Are the workers finished...
I'm working ......
Are the workers finished...
I'm working ......
Are the workers finished...
I'm working ......
Are the workers finished...
I'm working ......
Are the workers finished...
I'm working ......
Are the workers finished...
I'm working ......
Are the workers finished...
I'm working ......
Are the workers finished...
After finishing the work, I handed in 12
As shown in the preceding example, futuretask plays the role of supervisor. The landlord (main process) can check whether the supervisor's work is completed by constantly asking the Supervisor (isdone () method, the supervisor is asked to receive the result (get () method) after completing the work ).