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

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

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

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

final BlockingDequeue queue = new LinkedBlockingDequeue(); 

以下是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); 

这是使用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); 

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

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

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

 timer.cancel(); 

如果您使用ScheduledExecutorService,则可以执行此操作

 scheduler.shutdown(); 

您有两个不相关的要求:

  1. 生成随机数
  2. 每2分钟执行一次任务。

要每2分钟执行任何操作,您可以使用ScheduledExecutorService。

 import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.JFrame; import javax.swing.Timer; public class TimerExample { Random rand = new Random(); static int currRand; TimerExample() { currRand = rand.nextInt(99); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { currRand = rand.nextInt(99); } }; Timer timer = new Timer(2000, actionListener); timer.start(); } public static void main(String args[]) throws InterruptedException { TimerExample te = new TimerExample(); while( true ) { Thread.currentThread().sleep(500); System.out.println("current value:" + currRand ); } } } 

编辑:当然你应该在新的Timer(2000,actionListener)中设置2000; 两分钟到12万。

您可以使用目标环境中可用的任何计划function(例如, cronat ,Windows计划任务等),安排程序每两分钟运行一次。

或者您可以使用Thread#sleep方法暂停应用程序2,000ms并在循环中运行代码:

 while (loopCondition) { /* ...generate random number... */ // Suspend execution for 2 minutes Thread.currentThread().sleep(1000 * 60 * 2); } 

(这只是示例代码,您需要处理InterruptedException等。)

我不完全确定我理解这个问题。 如果您希望每两分钟生成一个不同的随机数,只需每两分钟调用一次rnd函数。

这可能就像(伪代码)一样简单:

 n = rnd() repeat until finished: use n for something sleep for two minutes n = rnd() 

如果你想继续使用相同的随机数两分钟并生成一个新的:

 time t = 0 int n = 0 def sort_of_rnd(): if now() - t > two minutes: n = rnd() t = now() return n 

这将继续返回相同的数字两分钟。