Java 8:并行FOR循环 [英] Java 8: Parallel FOR loop

查看:1779
本文介绍了Java 8:并行FOR循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说Java 8提供了许多有关并发计算的实用程序.因此,我想知道并行化给定for循环的最简单方法是什么?

I have heard Java 8 provides a lot of utilities regarding concurrent computing. Therefore I am wondering what is the simplest way to parallelise the given for loop?

public static void main(String[] args)
{
    Set<Server> servers = getServers();
    Map<String, String> serverData = new ConcurrentHashMap<>();

    for (Server server : servers)
    {
        String serverId = server.getIdentifier(); 
        String data = server.fetchData();

        serverData.put(serverId, data);
    }
}

推荐答案

Read up on streams, they're all the new rage.

特别要注意并行性:

带有显式for循环的处理元素本质上是串行的.流通过将计算重新格式化为聚合操作的流水线而不是对每个单独元素的命令性操作来促进并行执行.所有流操作都可以串行或串行执行并行."

"Processing elements with an explicit for-loop is inherently serial. Streams facilitate parallel execution by reframing the computation as a pipeline of aggregate operations, rather than as imperative operations on each individual element. All streams operations can execute either in serial or in parallel."

因此,回顾一下,没有并行的for循环,它们本质上是串行的.但是,流可以完成这项工作.看一下下面的代码:

So to recap, there are no parallel for-loops, they're inherently serial. Streams however can do the job. Take a look at the following code:

    Set<Server> servers = getServers();
    Map<String, String> serverData = new ConcurrentHashMap<>();

    servers.parallelStream().forEach((server) -> {
        serverData.put(server.getIdentifier(), server.fetchData());
    });

这篇关于Java 8:并行FOR循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆