在Java跨平台中无时间播种随机生成器

在Java跨平台中无时间播种随机生成器

本文介绍了在Java跨平台中无时间播种随机生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎同时在两个线程上初始化两个随机数生成器,并且我希望两个生成器的行为完全不同.我会经常在两个生成器上一个接一个地调用Random.nextInt(7).使用System.currentTimeMillis()并不是一个好主意,因为看起来我的计算机是如此之快,以至于我从两个生成器得到的数字很有可能是相同的.那么,有什么方法可以配置Random,以便尽管它们被一个接一个地调用,但它们的行为仍然有所不同?我希望该解决方案能够跨平台兼容,因此任何特定于平台的想法(例如从/dev/random中读取)都是不可接受的.感谢您的帮助.

I'm initializing two random number generators on two threads almost simultaneously and I want the two generators behaves completely different. I will call Random.nextInt(7) on two generators one right after another very often. Using System.currentTimeMillis() is not a good idea because it looks like my computer is so fast that there's a large chance that the number I get from the two generators are the same. So is there any way to config the Random so that though they are called one right after another, they still behave differently? I want the solution to be cross-platform compatible so any platform-specific idea such as read from /dev/random is not acceptable. Thanks for help.

推荐答案

一种方法:使用UUID(GUID)将每个随机实例播种(转换为哈希(但可能不仅仅是转换))为long.

One way: Seed each Random instance with a UUID (GUID) converted (hashed? but probably not just a cast) to a long.

其他答案建议使用 nanoTime ,这可能取决于硬件的速度,但我更喜欢UUID路由.

Other answers suggest using nanoTime, which may be suitable depending on the speed of the hardware, but I prefer the UUID route.

这篇关于在Java跨平台中无时间播种随机生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 14:43