所以我有一个正在运行的方法和一个设置为false的布尔变量。在运行时,变量可能设置为true,并且我希望方法在发生这种情况时暂停。
我认为这可能有用
if(variable) statement1;
else myPauseMethod();
if(variable) statement2;
else myPauseMethod();
//all other statements
但是它看起来很糟糕,因为我还有很多其他陈述。还有其他想法吗?
使用Thread#sleep(long)
暂停线程。
Thread#sleep(long)
暂停当前线程的参数。
如果要wait直到结果确认,请使用Example-2之类的方法。
不建议在主线程上使用Thread.sleep(long)
,因为它会停止当前线程。
不使用不休眠的无限循环是导致完全使用内核的原因。
public void myPauseMethod(){
try{
Thread.sleep(1000L);
}catch(InterruptException ignored){}
}
Example-2
public boolean waitUntilResult() throws InterruptException{
// Request method have to run at another thread.
// If not, method will be block forever.
requestResult();
while(!complete){
Thread.sleep(1L);
}
return result;
}