gpt4 book ai didi

java 8并行流混淆/问题

转载 作者:行者123 更新时间:2023-12-02 14:56:03 26 4
gpt4 key购买 nike

我是并行流的新手,正在尝试制作 1 个示例程序来计算值 * 100(1 到 100)并将其存储在 map 中。在执行代码时,我在每次迭代中得到不同的计数。我可能在某个地方错了,所以请知道正确方法的人指导我。

代码:

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.stream.Collectors;

public class Main{
static int l = 0;
public static void main (String[] args) throws java.lang.Exception {
letsGoParallel();
}
public static int makeSomeMagic(int data) {
l++;
return data * 100;
}
public static void letsGoParallel() {
List<Integer> dataList = new ArrayList<>();
for(int i = 1; i <= 100 ; i++) {
dataList.add(i);
}
Map<Integer, Integer> resultMap = new HashMap<>();
dataList.parallelStream().map(f -> {
Integer xx = 0;
{
xx = makeSomeMagic(f);
}
resultMap.put(f, xx);
return 0;
}).collect(Collectors.toList());
System.out.println("Input Size: " + dataList.size());
System.out.println("Size: " + resultMap.size());
System.out.println("Function Called: " + l);
}
}

Runnable Code

最后输出

Input Size: 100

Size: 100

Function Called: 98

每次运行输出都不同。我想在我自己的应用程序中使用并行流,但由于这种混淆/问题我不能。在我的应用程序中,我有 100-200 个唯一数字,需要对其执行一些相同的操作。简而言之,有处理某些事情的函数。

最佳答案

您对 HashMapl 变量的访问都是线程安全的,这就是为什么每个变量的输出都不同跑。

正确的方法是将 Stream 元素收集到 Map 中:

Map<Integer, Integer> resultMap =
dataList.parallelStream()
.collect(Collectors.toMap (Function.identity (), Main::makeSomeMagic));

编辑:l 变量仍然以线程安全方式更新此代码,因此如果最终值,您必须添加自己的线程安全这个变量对你很重要。

关于java 8并行流混淆/问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52828813/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com