ExecutorService提交任务后如何获取结果

发布时间:2025-08-14 01:58:17 作者:小樊
来源:亿速云 阅读:96

在Java中,使用ExecutorService提交任务后,可以通过以下两种方法获取结果:

  1. 使用Future对象:

当你使用ExecutorService.submit()方法提交一个实现了Callable接口的任务时,它会返回一个Future对象。你可以通过调用Future对象的get()方法来获取任务的执行结果。get()方法会阻塞,直到任务完成并返回结果。

示例:

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        Callable<Integer> task = () -> {
            Thread.sleep(2000);
            return 42;
        };

        Future<Integer> future = executorService.submit(task);

        // 获取任务结果
        Integer result = future.get();
        System.out.println("任务结果: " + result);

        executorService.shutdown();
    }
}
  1. 使用CompletionService

CompletionService是一个接口,它可以将任务的提交和结果的获取分离。你可以使用Executors.newCompletionService()方法创建一个CompletionService实例。然后,你可以使用submit()方法提交任务,并使用take()poll()方法获取已完成任务的结果。

示例:

import java.util.concurrent.*;

public class Main {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        CompletionService<Integer> completionService = Executors.newCompletionService<>(executorService);

        Callable<Integer> task = () -> {
            Thread.sleep(2000);
            return 42;
        };

        // 提交任务
        completionService.submit(task);

        // 获取已完成任务的结果
        Future<Integer> completedFuture = completionService.take();
        Integer result = completedFuture.get();
        System.out.println("任务结果: " + result);

        executorService.shutdown();
    }
}

这两种方法都可以用于获取ExecutorService提交任务后的结果。Future对象适用于单个任务的场景,而CompletionService适用于多个任务并且需要按完成顺序处理结果的场景。

推荐阅读:
  1. PHP、Java des的加密解密是什么意思
  2. 利用Java与PHP进行Web开发有什么区别

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:Ansible与云服务如何结合使用

下一篇:如何利用Java ExecutorService优化代码结构

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》