爱喝咖啡的程序员 2020-01-13 15:16 采纳率: 0%
浏览 239

为什么给一个线程私有的Random设置了种子后,在多线程环境下,输出new Random(47).nextInt(3)的值是随机的呢?

下面是我的测试用例,请指教!

public class Test {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        for(int i = 0; i < 10; i++) {
           exec.execute(new LocalThread());
        }
    }
}

class LocalThread implements Runnable{
    private final Random rand = new Random(47);

    @Override
    public void run() {
        try {
            while(!Thread.interrupted()) {
                System.out.println(Thread.currentThread().getId() + " - " + rand.nextInt(3));
                TimeUnit.MILLISECONDS.sleep(100);
            }
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

输出:

0 - 2
3 - 2
2 - 2
1 - 2
4 - 2
2 - 2
4 - 2
0 - 2
1 - 2
3 - 2
3 - 1
2 - 1
0 - 1
4 - 1
1 - 1

把暂停去掉

class LocalThread implements Runnable{
    private final Random rand = new Random(47);
    private final int id;
    public LocalThread(int id) {
        this.id = id;
    }

    @Override
    public void run() {
        while(!Thread.interrupted()) {
            System.out.println(id + " - " + rand.nextInt(3));
        }
    }
}

输出

1 - 1
1 - 1
1 - 0
1 - 2
1 - 0
1 - 0
1 - 2
1 - 0
1 - 1
1 - 2
0 - 0
0 - 1
3 - 0
...

  • 写回答

1条回答 默认 最新

  • data_jieyan 2020-01-13 17:24
    关注
    public class TestRandom {
        public static void main(String[] args) {
            ExecutorService exec = newCachedThreadPool();
            for (int i = 0; i < 4; i++) {
                exec.execute(new LocalThread());
            }
        }
    }
    
    class LocalThread implements Runnable {
        private final Random rand = new Random(47);
    
        @Override
        public void run() {
            int total = 1;
            try {
                while (total <= 5) {
                    System.out.println(Thread.currentThread().getId() + " - " + total + "-" + rand.nextInt(3));
                    total++;
                    TimeUnit.MILLISECONDS.sleep(3000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    

    这是我改了时间和增加打印运行次数的例子 结果就是下面

    11 - 1-2
    13 - 1-2
    12 - 1-2
    14 - 1-2
    13 - 2-2
    11 - 2-2
    12 - 2-2
    14 - 2-2
    11 - 3-1
    13 - 3-1
    12 - 3-1
    14 - 3-1
    11 - 4-2
    12 - 4-2
    13 - 4-2
    14 - 4-2
    12 - 5-1
    11 - 5-1
    13 - 5-1
    14 - 5-1
    

    每个线程的序列都是 2 2 1 2 1 这个就是这个种子伪随机创建出来的随机序列

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考