如何在设定的时间间隔生成随机数? [英] How to generate random numbers at set time intervals?

查看:61
本文介绍了如何在设定的时间间隔生成随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have developed code in Java for generating ten random numbers from a range 0 to 99. The problem is I need to generate a random number for every 2 min. I am new to this area and need your views.

推荐答案

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

This example adds a random number to a blocking dequeue every two minutes. You can take the numbers from the queue when you need them. You can use java.util.Timer as a lightweight facility to schedule the number generation or you can use java.util.concurrent.ScheduledExecutorService for a more versatile solution if you need more sophistication in the future. By writing the numbers to a dequeue, you have a unified interface of retrieving numbers from both facilities.

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

First, we set up the blocking queue:

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

这是 java.utilTimer 的设置:

Here is the setup with 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 的设置

This is the setup with 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);

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

Now, you can get a new random number from the queue every two minutes. The queue will block until a new number becomes available...

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

完成后,您可以终止调度程序.如果您使用了计时器,只需执行

Once you are done, you can terminate the scheduler. If you used the Timer, just do

timer.cancel();

如果你使用了 ScheduledExecutorService,你可以做到

If you used ScheduledExecutorService you can do

scheduler.shutdown();

这篇关于如何在设定的时间间隔生成随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆