Java的“ Parallel.For”吗?

Java的“ Parallel.For”吗?,第1张

Java的“ Parallel.For”吗?

我猜最接近的是:

ExecutorService exec = Executors.newFixedThreadPool(SOME_NUM_OF_THREADS);try {    for (final Object o : list) {        exec.submit(new Runnable() { @Override public void run() {     // do stuff with o. }        });    }} finally {    exec.shutdown();}

根据TheLQ的评论,您可以将SUM_NUM_THREADS设置为

Runtime.getRuntime().availableProcessors();

编辑:决定添加一个基本的“ Parallel.For”实现

public class Parallel {    private static final int NUM_CORES = Runtime.getRuntime().availableProcessors();    private static final ExecutorService forPool = Executors.newFixedThreadPool(NUM_CORES * 2, new NamedThreadFactory("Parallel.For"));    public static <T> void For(final Iterable<T> elements, final Operation<T> operation) {        try { // invokeAll blocks for us until all submitted tasks in the call complete forPool.invokeAll(createCallables(elements, operation));        } catch (InterruptedException e) { e.printStackTrace();        }    }    public static <T> Collection<Callable<Void>> createCallables(final Iterable<T> elements, final Operation<T> operation) {        List<Callable<Void>> callables = new linkedList<Callable<Void>>();        for (final T elem : elements) { callables.add(new Callable<Void>() {     @Override     public Void call() {         operation.perform(elem);         return null;     } });        }        return callables;    }    public static interface Operation<T> {        public void perform(T pParameter);    }}

Parallel.For的示例用法

// Collection of items to process in parallelCollection<Integer> elems = new linkedList<Integer>();for (int i = 0; i < 40; ++i) {    elems.add(i);}Parallel.For(elems,  // The operation to perform with each item new Parallel.Operation<Integer>() {    public void perform(Integer param) {        System.out.println(param);    };});

我想这个实现实际上更类似于Parallel.ForEach

编辑
如果有人有兴趣,我将其放在GitHub上。在GitHub上并行



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5175820.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-18
下一篇 2022-11-18

发表评论

登录后才能评论

评论列表(0条)

保存