有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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


共 (5) 个答案

  1. # 1 楼答案

    您有两个不相关的需求:

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

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

  2. # 2 楼答案

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

    它将在两分钟内继续返回相同的编号

  3. # 3 楼答案

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

    或者,您可以使用^{}方法将应用程序挂起2000毫秒,并在循环中运行代码:

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

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

  4. # 4 楼答案

    此示例每两分钟向阻塞出列添加一个随机数。您可以在需要时从队列中提取号码。您可以使用java。util。计时器是一种轻量级工具,用于计划数字生成,也可以使用java。util。同时发生的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。同时发生的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();
    
  5. # 5 楼答案

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

    编辑:当然你应该在新定时器中设置2000(2000,actionListener);到12万,持续两分钟