我编写了一个简单的自动单击脚本,它运行良好,因为每次我认为都应该单击它.我想知道的一件事是,它被延迟了2500毫秒到5000毫秒之间的随机间隔.我不是100%正在这样做吗?
所有代码都在这里:
public static void click(int desiredAmount)
{
int counter = 0;
Random rand = new Random();
while (counter < desiredAmount)
{
try {
Thread.sleep(rand.nextInt(5000-2500) + 2500);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
robot.mousePress(MouseEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(MouseEvent.BUTTON1_DOWN_MASK);
++counter;
}
}
只是执行点击的简单方法,我的担忧就出现在了这行代码Thread.sleep(rand.nextInt(5000-2500)2500)上;
我正在使用nextInt(int x)方法来获取两个值之间的随机INT,但是Thread.sleep();我使用的方法花了很长时间作为参数.这是否意味着将截断?而不是2500毫秒,而是2秒?还是3秒或4秒,而不是2646毫秒或3876毫秒等?
它实际上将每次点击的延迟时间从2500-5000随机延迟了几毫秒吗?我很难弄清楚这一点.
解决方法:
由于nextInt上限是互斥的,因此延迟值为2500到4999之间的随机数.从Java SE Specification开始:
public int nextInt(int bound)
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator’s sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All bound possible int values are produced with (approximately) equal probability.
rand.nextInt(5000-2500)2500与rand.nextInt(2500)2500相同(我认为这是一种更干净的编写方式).
同样,int值也可以转换为long而不丢失信息(long的范围比int宽,因此没有问题).从Java SE Specification开始:
A conversion from type int to type long requires run-time sign-extension of a 32-bit integer value to the 64-bit long representation. No information is lost.
最后,关于随机不是真正的随机,您是对的,它是伪随机的(这意味着所有可能的数字不是完全相等的概率,而是近似相等的概率).我不确定您将这段代码用于什么,但是我认为这足够满足您的需求.
您可以看一下关于给定范围内java中随机值的this post.
和this post有关随机随机性.
PD:您的代码(imho)的一个不错的改进是将rand变量设为private静态,而不是local.
标签:sleep,java
来源: https://codeday.me/bug/20191119/2034236.html