【发布时间】:2010-02-06 10:52:07
【问题描述】:
我用 Java 开发了代码,用于生成 0 到 99 范围内的十个随机数。问题是我需要每 2 分钟生成一个随机数。我是这个领域的新手,需要您的意见。
【问题讨论】:
我用 Java 开发了代码,用于生成 0 到 99 范围内的十个随机数。问题是我需要每 2 分钟生成一个随机数。我是这个领域的新手,需要您的意见。
【问题讨论】:
此示例每两分钟向阻塞出队添加一个随机数。您可以在需要时从队列中取出号码。您可以使用 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();
【讨论】:
您有两个不相关的要求:
要每 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 );
}
}
}
编辑:当然你应该在 new Timer(2000, actionListener); 中设置 2000;到 120 000 两分钟。
【讨论】:
您可以使用目标环境中可用的任何调度功能(例如,cron、at、Windows 计划任务等)安排您的程序每两分钟运行一次。
或者您可以使用Thread#sleep 方法将您的应用程序挂起 2,000 毫秒并循环运行您的代码:
while (loopCondition) {
/* ...generate random number... */
// Suspend execution for 2 minutes
Thread.currentThread().sleep(1000 * 60 * 2);
}
(这只是示例代码,您需要处理 InterruptedException 等。)
【讨论】:
sleep 的全部要点。请注意,这不是我的第一个建议。
我不完全确定我理解这个问题。如果您希望每两分钟生成一个不同的随机数,只需每两分钟调用一次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
它将在两分钟内继续返回相同的数字。
【讨论】: