为什么多线程产生一样的随机数?是写法错误吗?
另外,如果换成 Random实例,为什么就不一样了,不是说前者仅是后者的优化吗?
public class Task implements Runnable {
private static Random random = ThreadLocalRandom.current();
// private static Random random = new Random();
@Override
public void run() {
System.out.println(random.nextInt());
}
public static void main(String[] args) {
ExecutorService taskPool = Executors.newCachedThreadPool();
for(int n = 1; n < 10; n++) {
taskPool.submit(new Task());
}
taskPool.shutdown();
}
}
-1667209487
-1667209487
-1667209487
-1667209487
-1667209487
-1667209487
-1667209487
-1667209487
-1667209487
-1999664185
1468557546
183343793
770001684
1625714058
-2134889142
1456310974
-191722744
1763443594
每个线程都是15,30,14,这就是为啥是伪随机数