Related Topics

JAVA Programming
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableExample {
public static void main(String[] args) throws Exception {
// Create an ExecutorService with a fixed thread pool size of 1
ExecutorService executor = Executors.newFixedThreadPool(1);
// Create a Callable task
Callable<String> callableTask = new Callable<String>() {
public String call() throws Exception {
// Perform some time-consuming task
Thread.sleep(1000);
// Return a result
return "Task completed";
}
};
// Submit the task to the ExecutorService and obtain a Future object
Future<String> future = executor.submit(callableTask);
// Wait for the task to complete and obtain the result
String result = future.get();
System.out.println(result);
// Shutdown the ExecutorService
executor.shutdown();
}
}
In this example, a Callable task is created to perform a time-consuming task and return a result. The task is submitted to an ExecutorService using the submit() method, which returns a Future object that can be used to obtain the result of the task once it has completed. The get() method is called on the Future object to wait for the task to complete and obtain the result. Finally, the ExecutorService is shutdown.




Popular Category
Topics for You
Go through our study material. Your Job is awaiting.