java - 在java中并行化任务的最简单方法是什么?

标签 java multithreading parallel-processing

假设我有一个任务,例如:

for(Object object: objects) {
    Result result = compute(object);
    list.add(result);
}

并行化每个compute()的最简单方法是什么(假设它们已经是可并行化的)?

我不需要与上面的代码严格匹配的答案,只需一个一般答案。但如果您需要更多信息:我的任务是 IO 绑定(bind)的,这是针对 Spring Web 应用程序的,并且任务将在 HTTP 请求中执行。

最佳答案

我建议您查看 ExecutorService .

特别是这样的:

ExecutorService EXEC = Executors.newCachedThreadPool();
List<Callable<Result>> tasks = new ArrayList<Callable<Result>>();
for (final Object object: objects) {
    Callable<Result> c = new Callable<Result>() {
        @Override
        public Result call() throws Exception {
            return compute(object);
        }
    };
    tasks.add(c);
}
List<Future<Result>> results = EXEC.invokeAll(tasks);

请注意,如果 objects 是一个很大的列表,那么使用 newCachedThreadPool 可能会很糟糕。缓存的线程池可以为每个任务创建一个线程!您可能想要使用 newFixedThreadPool(n) ,其中 n 是合理的值(例如您拥有的核心数量,假设compute() 受 CPU 限制)。

以下是实际运行的完整代码:

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
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;

public class ExecutorServiceExample {
    private static final Random PRNG = new Random();

    private static class Result {
        private final int wait;
        public Result(int code) {
            this.wait = code;
        }
    }

    public static Result compute(Object obj) throws InterruptedException {
        int wait = PRNG.nextInt(3000);
        Thread.sleep(wait);
        return new Result(wait);
    }

    public static void main(String[] args) throws InterruptedException,
        ExecutionException {
        List<Object> objects = new ArrayList<Object>();
        for (int i = 0; i < 100; i++) {
            objects.add(new Object());
        }

        List<Callable<Result>> tasks = new ArrayList<Callable<Result>>();
        for (final Object object : objects) {
            Callable<Result> c = new Callable<Result>() {
                @Override
                public Result call() throws Exception {
                    return compute(object);
                }
            };
            tasks.add(c);
        }

        ExecutorService exec = Executors.newCachedThreadPool();
        // some other exectuors you could try to see the different behaviours
        // ExecutorService exec = Executors.newFixedThreadPool(3);
        // ExecutorService exec = Executors.newSingleThreadExecutor();
        try {
            long start = System.currentTimeMillis();
            List<Future<Result>> results = exec.invokeAll(tasks);
            int sum = 0;
            for (Future<Result> fr : results) {
                sum += fr.get().wait;
                System.out.println(String.format("Task waited %d ms",
                    fr.get().wait));
            }
            long elapsed = System.currentTimeMillis() - start;
            System.out.println(String.format("Elapsed time: %d ms", elapsed));
            System.out.println(String.format("... but compute tasks waited for total of %d ms; speed-up of %.2fx", sum, sum / (elapsed * 1d)));
        } finally {
            exec.shutdown();
        }
    }
}

关于java - 在java中并行化任务的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57966097/

相关文章:

使用 winsock 和 std::thread 的 C++ 多线程服务器

perl - Perl脚本的并行化

linux - 如何使用 bash 等到所有服务并行启动?

java - Spring如何过滤ApplicationEvents

java - 为什么在使用 printf 时出现运行时错误?

java - 我可以将 FlatfileItemReader 与 Taskexecutor 一起使用吗?

linux - 如何设置 OpenMP 以使用整个超线程进行并行处理?

java - 使用 JPA 规范指定结果限制

java - 使用StanfordCoreNLP提取两个实体之间的关系

c++ - Win32 临界区与互斥性能