Java 8: Parallel FOR loop

后端 未结 5 1417
独厮守ぢ
独厮守ぢ 2020-12-07 22:40

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?

5条回答
  •  太阳男子
    2020-12-07 23:04

    using my Parallel.For, your code might look like the following,

    public staic void main(String[] args)
    {
        Set servers = getServers();
        Map serverData = new ConcurrentHashMap<>();
    
        Parallel.ForEach(servers, new LoopBody()
        {
            public void run(Server server)
            {
                 String serverId = server.getIdentifier(); 
                 String data = server.fetchData();
    
                 serverData.put(serverId, data);
            }
        });
    }     
    

提交回复
热议问题