Tag: Package sys task returns ring nbsp Color try + +
The callable interface in Java is designed to enhance the functionality of the Runnable interface, but it is not a sub-interface of the Runnable interface. The call () method is provided as the thread execution body, but it has two different places than the runnable run () method:
1, the method needs to throw an exception, 2, the method can have a return value.
Callable cannot be a thread's target, its call return value is not humming directly, Java provides the future interface, and the Futuretask class implements the interface and Runnable interface, This allows you to wrap the callable interface with the Futuretask class and use it as the targe of the thread.
The way to the future:
1. Boolean Cancel (Boolean), cancels the callable class associated with the future;
2, V get (); Returns the execution result of the call method in callable, and once the method is called, the thread that invokes the method blocks until the child thread ends;
3, V get (long timeout,timeunit unit), throw timeoutexception if not returned within the time specified by the parameter.
4. Boolean iscancelled (); Returns true if the callable task is canceled before normal completion;
5, Boolean isDone (); Callable the task is complete returns true.
Implement the callable interface with the Rtnthread class, and because callable to specify a generic type, you need to specify the type when implementing the class.
Class RtnthreadImplements callable<integer>{
Public Integer call () {
int i =0;
for (; I <100; i++) {
System.Out.println (Thread.CurrentThread (). GetName () +"The loop variableIValues of:"+ i);
}
return i;
}
}
public class Callabletest {
public static void Main (string[] args) {
Rtnthread RT =New Rtnthread ();
futuretask<integer> task =New futuretask<integer> (RT);
Forint i =0; I <i++) {
System.Out.println ("In the main thread,IFor:"+ i);
if (i = = 20) {
new Thread (task," thread with return value "). Start ();
try {
System. out.println ("The return value of the child thread:" + task.get ());//The calling task obtains its return value, which causes the main thread to be blocked.
}catch (Exception e) {
}
}
}
}
}
Java's calablel future