Home  >  Article  >  Java  >  Java exception programming FutureTask instance analysis

Java exception programming FutureTask instance analysis

WBOY
WBOYforward
2023-06-03 17:10:051453browse

Explanation

1. The FutureTask class not only implements the Future interface but also implements the Runnable interface, which represents a Runnable that can generate results.

2. The FutureTask class implements the Future interface's methods of starting and canceling tasks, querying whether the task is completed, and obtaining calculation results.

To get the results of the FutureTask task, we can only get it by calling the getXXX() series of methods. These methods will be blocked when the results have not come out. At the same time, the task can be of Callable type (with a return result ), or it can be a Runnable type (no return result).

Example

private static void testFutureTask() throws ExecutionException, InterruptedException {
    System.out.println("-------------------- testFutureTask --------------------");
 
    // 创建一个 FutureTask(doOneThing 任务)
    FutureTask<String> futureTask = new FutureTask<>(FutureTaskDemo::doOneThing);
    // 使用线程池执行 doOneThing 任务
    ForkJoinPool.commonPool().execute(futureTask);
 
    // 执行 doOtherThing 任务
    String doOtherThingResult = doOtherThing();
 
    // 同步等待线程执行 doOneThing 任务结束
    String doOneThingResult = futureTask.get();
 
    // 任务执行结果输出
    System.out.println("doOneThingResult ---->>> " + doOneThingResult);
    System.out.println("doOtherThingResult ---->>> " + doOtherThingResult);
}

The above is the detailed content of Java exception programming FutureTask instance analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete