====== Send parameters to a thread and retrieve results from it in Java threads ======
To send parameters to a thread and retrieve results from it in Java, you typically use the **Callable** interface and **Future** objects.
The **Callable** interface is similar to Runnable, but it can return a value and throw exceptions.
A **Future** object represents the result of an asynchronous computation and can be used to retrieve the Callable's return value once the computation has completed.
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutionException;
// A class that implements Callable
class WordLengthCallable implements Callable {
private final String word;
public WordLengthCallable(String word) {
this.word = word;
}
@Override
public Integer call() {
// Returning the length of the word
return word.length();
}
}
public class CallableExample {
public static void main(String[] args) {
// Creating a thread pool with one thread
ExecutorService executor = Executors.newSingleThreadExecutor();
// Creating a callable object
WordLengthCallable callable = new WordLengthCallable("Hello, World");
// Submitting the callable to the executor and getting a Future object
Future future = executor.submit(callable);
try {
// Getting the result from the Future object
int length = future.get();
System.out.println("Length of the word: " + length);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
// Shutting down the executor
executor.shutdown();
}
}
**Callable Implementation**: The WordLengthCallable class implements Callable and overrides the call method. It takes a String parameter and returns the length of the string.
**ExecutorService**: The ExecutorService is used to manage and execute Callable tasks. In this example, a single-threaded executor is created.
**Submitting Callable**: The callable object is submitted to the executor using the submit method, which returns a Future object. This Future object represents the result of the Callable.
**Retrieving Result**: The future.get() method is used to retrieve the result of the Callable. This method blocks until the computation is complete.
**Handling Exceptions**: The code handles InterruptedException and ExecutionException, which can be thrown while waiting for the result.
**Shutting Down Executor**: Finally, the executor is shut down to prevent the program from running indefinitely.
This example demonstrates a clean way to pass parameters to a thread and retrieve results from it in Java.
Using **Callable** and **Future** makes it easier to manage threads and process their results, especially when dealing with tasks that return values or might throw exceptions.