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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2212848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 20:04:17  来源:igfitidea点击:

How to generate random numbers at set time intervals?

javarandomtimer

提问by Aravindkumar

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

回答by VoidPointer

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.

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

First, we set up the blocking queue:

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

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

Here is the setup with java.utilTimer:

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

This is the setup with java.util.concurrent.ScheduledExecutorService

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

If you used ScheduledExecutorService you can do

如果你使用 ScheduledExecutorService 你可以

scheduler.shutdown();

回答by stacker

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 );
        }
    }
}

EDIT: Of course you should set 2000 in new Timer(2000, actionListener); to 120 000 for two minutes.

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

回答by Peter Lawrey

You have two requirements which are unrelated:

您有两个不相关的要求:

  1. Generate random numbers
  2. Perform the task every 2 minutes.
  1. 生成随机数
  2. 每 2 分钟执行一次任务。

To do anything every 2 minutes you can use a ScheduledExecutorService.

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

回答by T.J. Crowder

You can schedule your program to be run once every two minutes using whatever scheduling features are available to you in your target environment (e.g., cron, at, Windows Scheduled Tasks, etc.).

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

Or you can use the Thread#sleepmethod to suspend your application for 2,000ms and run your code in a loop:

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

while (loopCondition) {
    /* ...generate random number... */

    // Suspend execution for 2 minutes
    Thread.currentThread().sleep(1000 * 60 * 2);
}

(That's just example code, you'll need to handle the InterruptedException and such.)

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

回答by paxdiablo

I'm not entirely sure I understand the problem. If you wish to generate a different random number every two minutes, simply call your rndfunction every two minutes.

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

This could be as simple as something like (pseudo-code):

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

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

If you want to keep using the same random number for two minutes and generate a new one:

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

time t = 0
int n = 0

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

which will continue to return the samenumber for a two minute period.

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