Callable and future
Java1.5 Start, Java provides the callable interface, the callable interface provides a call () method as the execution of the thread, but the call () method run () method is more powerful:
The call () method can have a return value
The call () method can declare an exception to be thrown
So we can provide a callable object as the target of thread, and the execution body of that thread is the call method of the callable object. The problem is that the callable object JDK1.5 start the new interface, and it is not a runnable sub-interface, so the callable object cannot be directly the target of the thread, and the call method has a return value, the calling method is not called directly, it is called as the thread's execution body. So how do you get the return value of the call method?
JDK1.5 begins to provide a future interface to represent the return value of the call method, and does not provide a Futuretask implementation class for the future interface, which implements the future interface and implements the Runnable interface to the target interface of the thread class.
Callable interface is also generic restriction, the type of generic parameter in the callable interface is the same as the return type of the call method
In the future interface, several public methods are defined to control its associated callable tasks.
Boolean mayinterruptifrunning: Attempt to cancel the callable task associated with the future
? V get (): Returns the return value of the call method in the callable task. Calling this method will cause the program to block and must wait until the child thread ends to get the return value
? V Get (Long timeout,timeunit unit): Returns the return value of the call method in the callable task, where the program blocks timeout and the time specified by the unit. Throws TimeoutException if no value has been returned after a specified time
? Boolean iscancelled (): Returns True if the callable task is canceled before it is properly completed
? Boolean IsDone (): Callable task completed returns true
The steps to create and start a thread with a return value are as follows
1) Create an implementation class for the callable interface, implementing the Call () method, which acts as the executing body of the thread, and the call () method has a return value
2) Create an instance of callable, use the Futuretask class to wrap the callable object, and the Futuretask object also encapsulates the return value of the call () method of the Callable object
3) Create and start a thread using the Futuretask object as the target of the thread instance
4) Call the method of the Futuretask object to get the return value after the child thread ends
And look back on the 24th day of Java