我执行了这堆代码:
int newOrderLow = ThreadLocalRandom.current().nextInt(50, shipCapacity / 3);
int newOrderUp = ThreadLocalRandom.current().nextInt(newOrderLow, shipCapacity + 1); // not lower than lower value
int newOrderMid = ThreadLocalRandom.current().nextInt(newOrderLow, newOrderUp + 1); // in between
Log.d(TAG, "New Order: {" + newOrderLow + ", " + newOrderMid + ", " + newOrderUp + "}");
并开始调试它。例如,当我将shipCapacity设置为600时,我在控制台中记录了这些数字:
New Order: {493, 772, 672}
有一点是上限不在[较低值范围内; shipCapacity + 1], 另一个是中间值结果。那么问题是什么?如何使用ThreadLocalRandom正确生成随机整数?
答案 0 :(得分:0)
您可能需要考虑运行以下测试代码:
@Test
public void test1() {
final int shipCapacity = 600;
for (int i = 0; i < 1000000; i++) {
int newOrderLow = ThreadLocalRandom.current().nextInt(50, shipCapacity / 3);
int newOrderUp = ThreadLocalRandom.current().nextInt(newOrderLow, shipCapacity + 1); // not lower than lower value
int newOrderMid = ThreadLocalRandom.current().nextInt(newOrderLow, newOrderUp + 1); // in between
System.out.println("numbers= " + newOrderLow + " " + newOrderUp + " " + newOrderMid);
assertThat(newOrderLow).isBetween(50, shipCapacity / 3);
assertThat(newOrderUp).isBetween(newOrderLow, shipCapacity + 1);
assertThat(newOrderMid).isBetween(newOrderLow, newOrderUp + 1);
}
我已经完成了这项工作,在我的机器上,您提到的规则似乎都没有被违反。
在我看来,问题出在其他地方,不在你提供的代码中,而是自己测试。