Obtain the return value of a thread in Java.
Java 5 adds the Callable interface to obtain the return value of a thread. Its usage is as follows:
Package com. ronniewang; import java. util. concurrent. callable; import java. util. concurrent. executionException; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. util. concurrent. future; public class detail {private static final int SLEEP_MILLS = 3000; private static final int SECOND_MILLS = 1000; private static int sleepSeconds = SLEEP_MILLS/SECOND_MILLS; ExecutorService executorService = Executors. newCachedThreadPool ();/*** when creating a multi-threaded program, we often implement the Runnable interface. Runnable has no return value. To obtain the return value, java 5 provides a new interface Callable */public static void main (String [] args) {new GetReturnValueFromCallable (). testCallable ();} private void testCallable () {/*** Callable must implement the call () method instead of the run () method, the type of the returned value is specified by the Callable type parameter. * Callable can only be set by ExecutorService. submit () is executed. After normal operation, a future object */Future <String> future = executorService will be returned. submit (new Callable <String> () {public String call () throws Exception {Thread. sleep (SLEEP_MILLS); return "I from callable" ;}}); while (true) {/*** before obtaining the future object, you can use the isDone () method to check whether the future object is complete, after completion, you can call the get () method to obtain the value of future. * if you call the get () method directly, the get () method will end the thread with the blocking value */if (future. isDone () {try {System. out. println (future. get (); break;} catch (InterruptedException e) {// ignored} catch (ExecutionException e) {// ignored} else {try {System. out. println ("after" + sleepSeconds -- + "seconds, we will get future"); Thread. sleep (SECOND_MILLS);} catch (InterruptedException e) {// ignored }}}}}
Output result:
After 3 seconds, we will get future
After 2 seconds, we will get future
After 1 seconds, we will get future
I from callable