【问题标题】:How to generate random numbers at set time intervals?如何以设定的时间间隔生成随机数?
【发布时间】:2010-02-06 10:52:07
【问题描述】:

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

【问题讨论】:

    标签: java random timer


    【解决方案1】:

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

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

    final BlockingDequeue<Integer> queue = new LinkedBlockingDequeue<Integer>();
    

    这里是 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.cancel();
    

    如果你使用了 ScheduledExecutorService,你可以这样做

    scheduler.shutdown();
    

    【讨论】:

    • Timer 类被认为已弃用,您应该改用 ScheduledExecutorService。
    • 好点。将示例更改为使用 ScheduledExecutorService
    • @Willi Schönborn,请不要虚构! stackoverflow.com/questions/2213109/…
    • 我说“考虑”已弃用。 ScheduledExecutorService 实际上是 Timer/TimerTask 组合的更通用替代品。
    • 也许这里的“弃用”太强了。很抱歉。
    【解决方案2】:

    您有两个不相关的要求:

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

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

    【讨论】:

      【解决方案3】:
      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 );
              }
          }
      }
      

      编辑:当然你应该在 new Timer(2000, actionListener); 中设置 2000;到 120 000 两分钟。

      【讨论】:

      • 对于这类问题,引入对 Swing 的依赖似乎有点矫枉过正。
      • 当然也可以使用 java.util.TimerTask 和 Timer。我只是扩展了一个现有的例子......
      【解决方案4】:

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

      或者您可以使用Thread#sleep 方法将您的应用程序挂起 2,000 毫秒并循环运行您的代码:

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

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

      【讨论】:

      • 等待很忙,效率很低。
      • @Willi:不,不是。这就是使用sleep 的全部要点。请注意,这不是我的第一个建议。
      • 从来没有说过。而阻塞当前线程甚至不是解决问题的办法。他希望每 2 秒生成一个随机数。阻塞并等待两秒钟而不做任何事情有什么意义?使用 ScheduledExecutorService 将是这里的最佳解决方案。 Thread.sleep(..) 几乎没有意义。
      • @Willi:你说这是“忙着等待”。它不是。是线程暂停。它的各种完全有效的用途,包括每隔几秒钟做一次而不引入进一步的依赖关系。不过,我认为我们大致同意这不是首选。
      • 如果在等待下一个数字生成时不需要做任何其他事情,这是最简单的解决方案。不,它不忙于等待。
      【解决方案5】:

      我不完全确定我理解这个问题。如果您希望每两分钟生成一个不同的随机数,只需每两分钟调用一次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
      

      它将在两分钟内继续返回相同的数字。

      【讨论】:

      • @Aravindkumar:请编辑您自己的问题并将代码放在那里。
      • 忙着等待,不要那样做。
      • 不,不一定是忙着等待。当您反复检查谓词而不知道它是否会成立时,就会发生忙等待。在这种情况下,谓词由等待时间决定,一旦等待两分钟,您就知道谓词成立。因此,在我看来,这不符合忙等待/旋转的条件。
      猜你喜欢
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      • 1970-01-01
      • 2014-06-12
      • 1970-01-01
      • 2016-08-14
      • 2011-10-03
      • 1970-01-01
      相关资源
      最近更新 更多