Java计时器每次在两个值之间的随机时间

Sve*_*art 1 java random swing timer

我有一个javax.swing.Timer需要在两个int之间的随机时间之后运行一个方法.

在创建对象之后,对象需要保持"运行"(就像在计时器中继续做事情一样).

我试过的:

private int minimal = 30;
private int Max = 1000;
int randomTimeOutput; 
Random randomTime;
Timer timerRunAction

public Object()
{
    randomTime = new Random();
    randomTimeOutput =  (minimal +
        randomTime.nextInt(Max - minimal + 1));
    timerRunAction = new Timer(randomTimeOutput, this);
    timerRunAction.start();
}

private void doSomething()
{
    //Do something
}

private void actionPerformed(ActionEvent e)
{
    dosomething();

}
Run Code Online (Sandbox Code Playgroud)

我已经更改了名称,使其更具可读性.对象不是真正的类.

但是会发生的事情是:计时器随机运行,但它会在第一次运行的随机时间内继续运行.

因此,每次完成运行后都不会改变时间.

我怎样才能让它发生,所以它每次都会以不同的时间运行?

And*_*ies 5

问题

Timer只被启动,并且对象被创建时你的代码中随机一次.每次向该Timer事件发送事件时ActionListener,除了呼叫之外没有任何事情发生doSomething().您的计时器延迟永远不会重新随机化.

考虑以下代码:

private int minimal = 30;
private int max = 1000;
int randomTimeOutput; 
Random randomTime;
Timer timerRunAction

public Object() {
    randomTime = new Random();
    randomTimeOutput =  (minimal + randomTime.nextInt(max - minimal + 1));
    timerRunAction = new Timer(randomTimeOutput, this);
    timerRunAction.start();
}

private void doSomething() {
    //Do something
}

private void updateTimer() {
    timerRunAction.stop();
    randomTimeOutput =  (minimal + randomTime.nextInt(max - minimal + 1));
    timerRunAction.setDelay(randomItemOutput);
    timerRunAction.restart();
}

public void actionPerformed(ActionEvent e) {
    dosomething();
    updateTimer();
}
Run Code Online (Sandbox Code Playgroud)

我添加了updateTimer()每次定时器发送ActionEvent给您的监听器时调用的方法.会发生什么是以下情况:

1-定时器"熄灭"并触发事件.
2-代码调用doSomething().
3-代码调用updateTimer().
4- updateTimer()首先停止计时器,然后选择一个新的随机数并保存到randomTimeOutput.
5- updateTimer()设置定时器的新延迟并重新启动它.

这实际上有效的是每次定时器触发一个事件时,它的延迟是随机的并且重新启动.

希望这有帮助.请在评论中提出任何问题.