最佳答案
我正在为一个服务器编写一个侦听器线程,目前我使用:
while (true){
try {
if (condition){
//do something
condition=false;
}
sleep(1000);
} catch (InterruptedException ex){
Logger.getLogger(server.class.getName()).log(Level.SEVERE, null, ex);
}
}
通过上面的代码,我遇到了 run 函数吞噬所有 CPU 时间循环的问题。睡眠功能起作用了,但它似乎只是一个权宜之计,而不是解决方案。
是否有一些函数会阻塞,直到变量“条件”变成“真”? 或者连续循环是等待变量值变化的标准方法?