您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,使用ExecutorService提交任务后,可以通过以下两种方法获取结果:
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();
}
}
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适用于多个任务并且需要按完成顺序处理结果的场景。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。