如何以设定的时间间隔生成随机数?

Ara*_*mar 1 java random timer

我已经开发了Java代码,用于生成0到99范围内的10个随机数.问题是我需要每2分钟生成一个随机数.我是这个领域的新手,需要你的意见.

Voi*_*ter 7

此示例每两分钟向一个阻塞队列中添加一个随机数.您可以在需要时从队列中获取数字.您可以使用java.util.Timer作为轻量级工具来计划数字生成,或者如果您将来需要更复杂的解决方案,则可以使用java.util.concurrent.ScheduledExecutorService来获得更通用的解决方案.通过将数字写入出列,您可以使用统一的界面从两个设施中检索数字.

首先,我们设置阻塞队列:

final BlockingDequeue<Integer> queue = new LinkedBlockingDequeue<Integer>();
Run Code Online (Sandbox Code Playgroud)

以下是java.utilTimer的设置:

TimerTask task = new TimerTask() {
    public void run() {
        queue.put(Math.round(Math.random() * 99));
        // or use whatever method you chose to generate the number...
    }
};
Timer timer = new Timer(true)Timer();
timer.schedule(task, 0, 120000); 
Run Code Online (Sandbox Code Playgroud)

这是使用java.util.concurrent.ScheduledExecutorService的设置

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Runnable task = new Runnable() {
    public void run() {
        queue.put(Math.round(Math.random() * 99));
        // or use whatever method you chose to generate the number...
    }
};
scheduler.scheduleAtFixedRate(task, 0, 120, SECONDS);
Run Code Online (Sandbox Code Playgroud)

现在,您可以每两分钟从队列中获取一个新的随机数.队列将阻塞,直到有新号码可用...

int numbers = 100;
for (int i = 0; i < numbers; i++) {
    Inetger rand = queue.remove();
    System.out.println("new random number: " + rand);
}
Run Code Online (Sandbox Code Playgroud)

完成后,您可以终止调度程序.如果你使用了Timer,就行了

timer.cancel();
Run Code Online (Sandbox Code Playgroud)

如果您使用ScheduledExecutorService,您可以这样做

scheduler.shutdown();
Run Code Online (Sandbox Code Playgroud)

  • 不推荐使用Timer. (5认同)
  • @WilliSchönborn,请不要搞砸!http://stackoverflow.com/questions/2213109/java-util-timer-is-is-deprecated (3认同)
  • 也许"弃用"在这里太强了.对不起. (2认同)