• java的Random


    首先,Point类

    public class Point {
        int x, y;
    
        public Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    
        boolean isSame() {
            return x == y;
        }
    }

    测试代码A:

    public class RandomTest {
    
        public static Random random = new Random();
        public static void main(String[] args) {
            int x = 0, y = 0;
            List<Point> points = new ArrayList<Point>();
            for (int i = 0; i < 100000; i++) {
                x = new Random().nextInt(20);
                y = new Random().nextInt(20);
                points.add(new Point(x, y));
            }
            System.out.println(getSameCount(points));
    
        }
    
        public static int getSameCount(List<Point> li) {
            int count = 0;
            for (Point point : li) {
                if (point.isSame())
                    count++;
            }
            return count;
        }
    
    }

    测试代码B将Main方法替换为

    public static void main(String[] args) {
            int x = 0, y = 0;
            List<Point> points = new ArrayList<Point>();
            for (int i = 0; i < 100000; i++) {
                x = random.nextInt(100);
                y = random.nextInt(100);
                points.add(new Point(x, y));
            }
            System.out.println(getSameCount(points));
    
        }

    经测试

    A代码打印结果在3000左右

    B代码打印结果在1000左右

    查了一些资料

    大概是因为同时创建的两个Random对象,产生随机数的算法会比较类似,和创建对象时的时间戳有关系,所以产生的随机数相同的几率也比较大。

    所以程序中应该尽量避免使用多个Random对象,或者直接使用Math.random();

    欢迎 意见 建议 指正 交流。

  • 相关阅读:
    zabbix执行远程命令
    zabbix监控主从同步
    s3fs+minio模拟挂载S3服务器到本地服务器
    PHP编译报错
    ldd可执行程序时返回not a dynamic executable
    Windows nessus安装
    Django数据库,在原有表中添加新字段
    docker安装fastdfs与java客户端测试
    Docker安装与启动
    2018HBCPC
  • 原文地址:https://www.cnblogs.com/xirtam/p/3145489.html
Copyright © 2020-2023  润新知