所以我有一个计时器,每隔几秒创建一个对象并将它们放入队列中。我正在运行一个 while 循环,如果队列为空或有人在其中,则打印出来。
while(1>0){
if(wait_list.isEmpty()){
System.out.println("Waiting");
}else{
System.out.println("Good");
}
}
}
效果很好,它会打印出“waiting”,直到有东西放入队列,然后打印“good”。第二次我尝试让它只打印一次,然后它就不会打印出 else 语句。它只打印一次“waiting”,然后不执行任何其他操作,即使将对象添加到队列中也是如此。
boolean wait = true;
while(1>0){
if(wait_list.isEmpty()){
if(wait == true){
System.out.println("Waiting");
wait = false;
}
}else{
System.out.println("Good");
}
}
我在这里错过了一些非常简单的东西吗?无限循环或其他东西(除了 while 循环)。
最佳答案
在“Good” block 中,您需要实际消耗队列中的值,并且需要重置 wait
标志。
下面是一个完全可运行的示例。队列的内容并不重要,所以我只是让它包含执行时间(计划的和实际的)。举个例子,我不想让它永远运行,所以永无止境的 while
循环被更改为在 10 个值后停止。为了表明可以足够快地添加多个值而无需打印“等待”,计时器将在大约 33% 的时间内添加 2 个值。
// Create queue, and task for adding values to queue
final ConcurrentLinkedQueue<Date[]> wait_list = new ConcurrentLinkedQueue<Date[]>();
TimerTask task = new TimerTask() {
@Override public void run() {
Date actualTime = new Date();
Date scheduledTime = new Date(this.scheduledExecutionTime());
wait_list.add(new Date[] { scheduledTime, actualTime });
if (actualTime.getTime() % 3 == 0) // Add two elements about 33% of the time
wait_list.add(new Date[] { scheduledTime, actualTime });
}
};
// Run task every 0.1 second
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, 100, 100);
// Process next 10 values, printing "Waiting" whenever queue goes empty
SimpleDateFormat fmt = new SimpleDateFormat("mm:ss.SSS");
boolean waiting = false;
int countDown = 10;
while (countDown > 0) {
if (wait_list.isEmpty()) {
if (! waiting) {
System.out.println("Waiting");
waiting = true;
}
} else {
Date[] date = wait_list.remove();
System.out.println("Good: scheduled=" + fmt.format(date[0]) + ", actual=" + fmt.format(date[1]));
waiting = false;
countDown--;
}
}
// Stop timer
timer.cancel();
输出
Waiting
Good: scheduled=57:49.708, actual=57:49.718
Waiting
Good: scheduled=57:49.808, actual=57:49.811
Waiting
Good: scheduled=57:49.908, actual=57:49.920
Good: scheduled=57:49.908, actual=57:49.920
Waiting
Good: scheduled=57:50.008, actual=57:50.014
Waiting
Good: scheduled=57:50.108, actual=57:50.123
Waiting
Good: scheduled=57:50.208, actual=57:50.217
Good: scheduled=57:50.208, actual=57:50.217
Waiting
Good: scheduled=57:50.308, actual=57:50.310
Good: scheduled=57:50.308, actual=57:50.310
关于java - 为什么 boolean 变量会阻止打印我的 else 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32446799/