threads
Return a value from a thread
This is an example of how to return the value of a Thread. The steps of the example are described in short:
- We have implemented two classes,
RetDoubleandRetIntthat both implement the Callable, the first using as parameter aDoubleand the second one using as parameter anInteger. They both override thecall()method of the Callable, and the first returns aDoublevalue, whereas the second one returns anInteger. - We create an ExecutorService, using
newFixedThreadPool(int nThreads)API method of Executors. The method returns a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. - The ExecutorService uses its
submit(CallableAPI method, for both Callables in order to submit a value-returning task for execution and returns two Future objects representing the pending results of the tasks.task) - In order to get the values of the Future objects, we can use their
get()API methods, that wait if necessary for the computation to complete, and then retrieve the result. - Finally the ExecutorService uses its
shutdown()API method to initiate an orderly shutdown, in which the previously submitted tasks are executed, but no new tasks will be accepted.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class RetVal {
public static void main(String args[]) throws Exception {
ExecutorService service = Executors.newFixedThreadPool(3);
Future<Double> retdouble = service.submit(new RetDouble());
Future<Integer> retInt = service.submit(new RetInt());
System.out.println(retdouble.get());
System.out.println(retInt.get());
service.shutdown();
}
}
class RetDouble implements Callable<Double> {
RetDouble() {
}
@Override
public Double call() {
return 2.0;
}
}
class RetInt implements Callable<Integer> {
RetInt() {
}
@Override
public Integer call() {
return 1;
}
}
Output:
2.0
1
This was an example of how to return the value of a Thread in Java.
