java - 通过生成随机数根据百分比随机选择表格

标签 java random

我正在开发一个项目,其中不同的数据库中有两个具有不同架构的表。这意味着我有两个不同的连接参数用于使用 JDBC 连接这两个表-

假设下面是 config.property 文件,其中 table1.percentage 表示 80% 的时间 table1 将被选取,并且 20% 的时间 table2 将根据随机数进行选择。

TABLES: table1 table2

#For Table1
table1.percentage: 80    

#For Table2
table2.percentage: 20

下面的方法将读取上面的config.property文件并为每个表创建一个ReadTableConnectionInfo对象。

private static HashMap<String, ReadTableConnectionInfo> tableList = new HashMap<String, ReadTableConnectionInfo>();

private static void readPropertyFile() throws IOException {

    prop.load(Read.class.getClassLoader().getResourceAsStream("config.properties"));

    tableNames = Arrays.asList(prop.getProperty("TABLES").split(" "));

    for (String arg : tableNames) {

        ReadTableConnectionInfo ci = new ReadTableConnectionInfo();

        double percentage = Double.parseDouble(prop.getProperty(arg + ".percentage"));

        ci.setPercentage(percentage);

    tableList.put(arg, ci);
    }
}

下面是 ReadTableConnectionInfo 类,它将保存特定表的所有表连接信息

public class ReadTableConnectionInfo {

    public String percentage;

    public double getPercentage() {
        return percentage;
    }

    public void setPercentage(double percentage) {
        this.percentage = percentage;
    }
}

现在,在我的运行方法中,每个线程必须生成随机数,然后根据每个表的百分比决定需要使用哪个表。

private static Random random = new SecureRandom();


@Override
public run() {
  ...


  while ( < 60 minutes) {
    double randomNumber = random.nextDouble() * 100.0;
    ReadTableConnectionInfo tableInfo = selectRandomConnection(randomNumber);

    // do query...
  }
}


//Any problem with the below method?
private ReadTableConnectionInfo selectRandomConnection(double randomNumber) {
  double limit = 0;
  for (ReadTableConnectionInfo ci : tableLists.values()) {
    limit += ci.getPercentage();
    if (randomNumber < limit) {
      return ci;
    }
      }
    throw new IllegalStateException();
   }

问题陈述:-

我的 selectRandomConnection 方法有什么问题吗?因为每个线程工作 60 分钟,并且在这 60 分钟内每次只选择 table1

我正在寻找的是它应该选择 table180% 时间和它应该选择 20% 的时间表2

最佳答案

如果您希望 A 在 80% 的情况下被选中,而 B 在 20% 的情况下被选中,则平均而言,只需选择 0(含)和 100(不含)之间的随机数即可。如果数量 < 80,则选择 A,否则选择 B。

就这么简单。

关于java - 通过生成随机数根据百分比随机选择表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15147017/

相关文章:

java - Firebase 数据库从子 android 访问节点

java - java中如何访问json数组元素

基于机会从列表中输出Java

java - 我如何处理/限制用户访问 servlet 和 jsp?

java - 如何顺利设置布局高度

linux - random() 在 Linux 中函数相同的值(同时 grof ing)

java - 如何在 t[][] 中对 a[] 中的整数进行随机排序,以使 a[] 中的所有整数彼此相邻?

mysql - 带 Where 子句的 Order By Rand()

java - 如何使用 Java Stream 逐行读取文件

c++ - 随机 std::array