这会暂停我的Java线程一分钟吗? [英] Will this pause my Java thread for a minute?
本文介绍了这会暂停我的Java线程一分钟吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
while(true){
this.doSomethingPeriodically();
Calendar now = Calendar.getInstance();
int minutes = now.get(Calendar.MINUTE);
int resume = minutes + 1;
while(now.get(Calendar.MINUTE)< resume){
//等待一分钟
}
}
解决方案这段代码永远不会离开循环。这是一个无限循环,因为
日历
实例由现在
指向不会改变。
此外,您尝试在此处执行的是实施忙等待<这是一个非常糟糕的主意(它使用CPU时间没有什么有趣的)。
正确的睡眠方式是使用
Thread。 / code>
sleep()
。Am I doing something really stupid here? I am trying to execute a method every minute or so, forever, or until I stop the program.
while(true) { this.doSomethingPeriodically(); Calendar now = Calendar.getInstance(); int minutes = now.get(Calendar.MINUTE); int resume = minutes + 1; while (now.get(Calendar.MINUTE) < resume) { // waiting for a minute } }
解决方案This code will never leave the loop. It's an endless loop, since the
Calendar
instance refered to bynow
won't change.Also, what you try to do here is implement busy waiting which is a very bad idea (it uses CPU time doing nothing interesting).
The correct way to sleep is to use
Thread.
sleep()
.这篇关于这会暂停我的Java线程一分钟吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文