dog*_*ane 14 java random java-7
我正在尝试使用Java 7的 ThreadLocalRandom,并发现它在多个线程中生成完全相同的随机数.
这是我的代码,我创建了5个线程,每个线程打印出5个随机数:
//5 threads
for(int i = 0; i < 5 ; i++) {
final Thread thread = new Thread() {
@Override
public void run() {
System.out.print(Thread.currentThread().getName()+":");
//each thread prints 5 random numbers
for(int j = 0 ; j < 5; j++) {
final int random = ThreadLocalRandom.current().nextInt(1,100);
System.out.print(random + ",");
}
System.out.println();
}
};
thread.start();
thread.join();
}
Run Code Online (Sandbox Code Playgroud)
输出:
Thread-0:1,93,45,75,29,
Thread-1:1,93,45,75,29,
Thread-2:1,93,45,75,29,
Thread-3:1,93,45,75,29,
Thread-4:1,93,45,75,29,
Run Code Online (Sandbox Code Playgroud)
为什么我为每个线程和每次执行程序获得相同的随机数?
谷歌搜索"ThreadLocalRandom源"给了我http://www.assembla.com/code/scala-eclipse-toolchain/git/nodes/src/forkjoin/scala/concurrent/forkjoin/ThreadLocalRandom.java
它的长/短:它使用一个ThreadLocal<ThreadLocalRandom>调用no-arg构造函数来构造
no-arg构造函数是
/**
* Constructor called only by localRandom.initialValue.
* We rely on the fact that the superclass no-arg constructor
* invokes setSeed exactly once to initialize.
*/
ThreadLocalRandom() {
super();
}
Run Code Online (Sandbox Code Playgroud)
Random中的no-arg super 使用唯一种子调用this(long)
不过那个构造函数呢
public Random(long seed) {
this.seed = new AtomicLong(initialScramble(seed));
}
Run Code Online (Sandbox Code Playgroud)
即不是文档的预期行为
和ThreadLocalRandom没有/不能使用私有 seed
| 归档时间: |
|
| 查看次数: |
6733 次 |
| 最近记录: |