您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
Java ExecutorService 是一个用于管理线程池和执行异步任务的接口,它可以帮助我们更容易地进行并行计算
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class ParallelTask implements Callable<Integer> {
private int id;
public ParallelTask(int id) {
this.id = id;
}
@Override
public Integer call() {
System.out.println("Task " + id + " is running on thread " + Thread.currentThread().getName());
try {
Thread.sleep(1000); // 模拟耗时操作
} catch (InterruptedException e) {
e.printStackTrace();
}
return id * 2;
}
}
public class ParallelComputationExample {
public static void main(String[] args) {
// 创建一个固定大小的线程池
ExecutorService executorService = Executors.newFixedThreadPool(4);
// 创建一个任务列表
List<ParallelTask> tasks = Arrays.asList(new ParallelTask(1), new ParallelTask(2), new ParallelTask(3), new ParallelTask(4));
try {
// 提交任务并获取 Future 列表
List<Future<Integer>> futures = executorService.invokeAll(tasks);
// 处理任务结果
for (Future<Integer> future : futures) {
try {
System.out.println("Result: " + future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 关闭 ExecutorService
executorService.shutdown();
}
}
}
在这个例子中,我们创建了一个固定大小为4的线程池,并提交了4个任务。invokeAll()
方法会等待所有任务完成,并返回一个包含任务结果的 Future 列表。我们可以遍历这个列表,使用 future.get()
方法获取每个任务的结果。
注意:在实际应用中,你可能需要根据实际需求调整线程池的大小以及其他参数。同时,不要忘记在任务完成后关闭 ExecutorService。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。