我正在为服务器编写一个监听器线程,目前我正在使用:
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 Code Online (Sandbox Code Playgroud)
使用上面的代码,我遇到了运行函数吃掉所有cpu时间循环的问题.睡眠功能有效,但它似乎是一个临时修复,而不是解决方案.
是否有一些函数会阻塞,直到变量'condition'变为'true'?或者是不断循环标准的等待方法,直到变量的值发生变化?
Java中是否有一个库可以执行以下操作?A thread应重复sleepx毫秒,直到条件变为真或达到最大时间.
当测试等待某些条件变为真时,这种情况通常发生.这种情况受到另一个人的影响thread.
[编辑]为了使它更清楚,我希望测试在失败前只等待X ms.它不能永远等待条件成为现实.我正在添加一个人为的例子.
class StateHolder{
boolean active = false;
StateHolder(){
new Thread(new Runnable(){
public void run(){
active = true;
}
}, "State-Changer").start()
}
boolean isActive(){
return active;
}
}
class StateHolderTest{
@Test
public void shouldTurnActive(){
StateHolder holder = new StateHolder();
assertTrue(holder.isActive); // i want this call not to fail
}
}
Run Code Online (Sandbox Code Playgroud)