栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java的“ Parallel.For”吗?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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上并行



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/449479.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号