Java 7: ThreadLocalRandom generating the same random numbers

自作多情 提交于 2019-11-29 11:58:20

问题


I'm trying out Java 7's ThreadLocalRandom and see that it is generating exactly the same random numbers across multiple threads.

Here is my code, in which I create 5 threads and each thread prints out 5 random numbers:

//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();
}

Output:

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,

Why am I getting the same random numbers for each thread and for every execution of the program?


回答1:


Seems like there's an open bug regarding this issue. See here and here




回答2:


googling for the "ThreadLocalRandom source" gave me http://www.assembla.com/code/scala-eclipse-toolchain/git/nodes/src/forkjoin/scala/concurrent/forkjoin/ThreadLocalRandom.java

long/short of it: it uses a ThreadLocal<ThreadLocalRandom> which calls the no-arg constructor for construction

that no-arg constructor is

/**
 * 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();
}

the no-arg super in Random calls this(long) with a unique seed

HOWEVER that constructor does

public Random(long seed) {
    this.seed = new AtomicLong(initialScramble(seed));
}

i.e. not the expected behavior from documentation

and ThreadLocalRandom doesn't/can't use the private seed




回答3:


Isn't this because the threads are being created at roughly the same time and thus getting seeded the same value from the timer? I was under the impression that was how that worked, though I may be mistaken.



来源:https://stackoverflow.com/questions/7139525/java-7-threadlocalrandom-generating-the-same-random-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!