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 楼答案
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 );
}
}
}
# 1 楼答案
您有两个不相关的需求:
要每2分钟执行一次操作,可以使用ScheduledExecutorService
# 2 楼答案
我不完全确定我是否理解这个问题。如果希望每两分钟生成一个不同的随机数,只需每两分钟调用
rnd
函数这可以像(伪代码)一样简单:
如果要继续使用相同的随机数两分钟并生成新的随机数:
它将在两分钟内继续返回相同的编号
# 3 楼答案
您可以使用目标环境中可用的任何调度功能(例如
cron
、at
、Windows调度任务等),将程序调度为每两分钟运行一次或者,您可以使用^{} 方法将应用程序挂起2000毫秒,并在循环中运行代码:
(这只是示例代码,您需要处理InterruptedException等。)
# 4 楼答案
此示例每两分钟向阻塞出列添加一个随机数。您可以在需要时从队列中提取号码。您可以使用java。util。计时器是一种轻量级工具,用于计划数字生成,也可以使用java。util。同时发生的ScheduledExecutorService提供了一个更通用的解决方案,如果您将来需要更复杂的解决方案。通过将数字写入出列,您就有了一个从两个设施检索数字的统一接口
首先,我们设置阻塞队列:
下面是java的设置。utilTimer:
这是java的设置。util。同时发生的ScheduledExecutorService
现在,您可以每两分钟从队列中获取一个新的随机数。队列将阻塞,直到新号码可用
完成后,可以终止调度程序。如果你用的是计时器,就这么做
如果您使用ScheduledExecutorService,您可以
# 5 楼答案
编辑:当然你应该在新定时器中设置2000(2000,actionListener);到12万,持续两分钟