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

Java exception programming FutureTask instance analysis

WBOY
Release: 2023-06-03 17:10:05
forward
1481 people have browsed it

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);
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template