The Callable interface has been provided since Java5. This interface is an enhanced version of the Runnable interface. The Callable interface provides a call() method as the thread execution body. The call() method There can be a return value, and the call() method can be declared to throw an exception.
boolean cancel(boolean may)
Try to cancel the associated Callable task in this Future.
V get()
Return the return value of the call() method in the Call task. Calling this method will cause the thread to block, and you must wait for the child thread to end before getting the return value.
V get(long timeout,TimeUnit unit)
Return the return value of the call() method in the Call task. This method allows the program to block for up to the time specified by timeout and unit. If the specified time passes, and if there is still no return value after the specified time, a TimeoutException exception will be thrown.
boolean isCancelled()
Returns true if the Callable task is canceled before it is completed normally.
boolean isDone()
Returns true if the Callable task has been completed.
Runnable implementation steps:
Create an implementation class of the Callable interface and implement the call() method. The call() The method serves as the execution body of the thread, and the call() method has a return value.
Use the FutureTask class to wrap the Callable object.
Use the FutureTask object as the target of the Thread object to create and start a new thread.
Enable the get() method of the FutureTask object to obtain the return value of the child thread.
<code>public class CallableDemo implements Callable<Integer> {<br> public static void main(String args[]) {<br> FutureTask<Integer> futureTask = new FutureTask<Integer>(new CallableDemo());<br> new Thread(futureTask).start();<br> try {<br> System.out.println("子线程返回值:" + futureTask.get());<br> } catch (InterruptedException e) {<br> e.printStackTrace();<br> } catch (ExecutionException e) {<br> e.printStackTrace();<br> }<br> if (futureTask.isDone()) {<br> System.out.println("线程结束");<br> }<br> }<br><br> @Override<br> public Integer call() throws Exception {<br> System.out.println("线程开始");<br> int ss = 0;<br> for (int i = 0; i < 20; i++) {<br> ss += i;<br> }<br> return ss;<br> }<br>}</code>
The above is the detailed content of How to implement the Callable interface to create a thread class in java. For more information, please follow other related articles on the PHP Chinese website!