有没有办法在Java中与种子并行创建一致的随机数?

寻找一种与种子并行创建随机数的方法。需要结果在所有运行中保持一致且唯一。

在下面的代码中,从多个线程访问Random导致两个断言均失败。 Random不是线程安全的,因此这是可以预期的。我期望使用SplittableRandom来获得唯一且一致的结果(均为断言),但不起作用。使用ThreadLocalRandom没有种子,因此无法提供一致的结果。

public static void main(String[] args){
    List<List<Double>> randomLists = IntStream.range(0,100)
        .mapToObject(j->getNextList(new Random(42)).collect(toList());
    validateListsHoldUniqueNumbers(list);    
    validateListsAreIdentical(list);
}

// original random
public static List<Double> getNextList(Random random){
    return IntStream.range(0,100).parallel.mapToDouble(i->random.nextLong()).sorted().boxed().collect(toList));
}

public static void validateListsHoldUniqueNumbers(List<List<Double>> randomLists){
    randomLists.forEach(randomList -> assert(new HashSet<>(randomList).size() == randomList.size());
}

public static void validateListsAreIdentical(List<List<Double>> randomLists){
   assert(new HashSet<>(randomLists).size() == 1)
}

这是SplittableRandom代码,应该是线程安全的-无效:

public static void main(String[] args){
    List<List<Double>> randomLists = IntStream.range(0,100)
        .mapToObject(j->getNextListsplittable(new SplittableRandom(42)).collect(toList());
    validateListsHoldUniqueNumbers(list);    
    validateListsAreIdentical(list);
}

public static List<Double> getNextListsplittable(SplittableRandom random){
    return IntStream.range(0,100).parallel.mapToDouble(i->random.split().nextLong()).sorted().boxed().collect(toList));
}

可拆分表是否被正确使用?真的是线程安全的吗?

LoongWalker 回答:有没有办法在Java中与种子并行创建一致的随机数?

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3151239.html

大家都在问