Java FutureTask: Step-by-Step Guide
FutureTask is a Java class used to represent an asynchronous task that may produce a result. It is commonly used in multi-thread programming, typically in conjunction with ExecutorService.
The general steps for using FutureTask are as follows:
- Create a Callable object that implements the call() method to execute tasks asynchronously. The return type of the call() method should be consistent with the generic type of FutureTask.
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
// 执行异步任务
return 42;
}
};
- Instantiate a FutureTask object with a Callable object as a parameter.
FutureTask<Integer> futureTask = new FutureTask<>(callable);
- Create a thread pool and submit FutureTask objects to the thread pool for execution.
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.submit(futureTask);
- You can retrieve the result of async tasks using the get() method of FutureTask. If the task is not yet completed, the get() method will block the current thread until the task is finished.
try {
Integer result = futureTask.get();
System.out.println("异步任务的结果是:" + result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
By following the above steps, you can use FutureTask to execute asynchronous tasks and obtain results.