There are three methods to create a Java thread.
1. inherit Thread class creation Thread
2. Implement the Runnable interface to create a thread
3. Use Callable and Future to create a thread
The first and second methods are commonplace. I will not talk about them here. I will mainly introduce the third method.
Java has provided the Callable interface since Java 5. It seems like an enhanced version of the Runnable interface. The Callable interface provides a call method that can be used as the thread's execution body, but call () methods are more powerful than run () methods.
The call () method can return values.
The call () method can declare that an exception is thrown.
Java 5 provides the Future interface to represent the return value of the call () method in the Callable interface, and provides a FutureTask implementation class for the Future interface. This implementation class implements the Future interface, can be used as the target of the Thread class.
The Future interface provides the following methods to control its associated Callable tasks:
Boolean cancel (boolean mayInterruptIfRunning): attempts to cancel the Callable task associated with the Future.
V get (): return the return value of the call () method. This method will cause program blocking and the return value must be obtained after the sub-thread ends.
V get (long timeout, TimeUnit unit): return the return value of the call () method, waiting for a specified time at most. If Callable still does not return the value at the specified time, a TimeoutException will be thrown.
Boolean isCancelled (): returns true if the Callable task is canceled before it completes.
Boolean isDone (): returns true if the Callable task is completed.
[Java]
Import java. util. concurrent. Callable;
Import java. util. concurrent. FutureTask;
Public class Test implements Callable <String> {
Public static void main (String [] args) throws Exception
{
Test t = new Test ();
FutureTask ft = new FutureTask (t );
Thread th = new Thread (ft, "sub-Thread ");
Th. start ();
System. out. println ("the result is" + ft. get ());
}
@ Override
Public String call () throws Exception {
// TODO Auto-generated method stub
Int I;
For (I = 0; I <10000; I ++)
{
System. out. println (I );
}
Return String. valueOf (I );
}
}