我有一个在我的测试应用程序中运行的线程,线程内有一个 while 循环。当 while 循环运行时,我想每 30 秒从这个 while 循环中执行一个方法。在 while 循环内,不想让线程 hibernate 或停止循环,它必须运行并且每 30 秒调用一次该方法。
Thread myThread = new Thread() {
@Override
public void run() {
//my code that runs with a loop
//while loop here that runs and needs to execute method every 30 seconds, if condition met continue else break;
};
myThread.start();
}
最佳答案
等待,你可以使用
Thread.sleep(milliseconds);
有关文档,请参阅 here
如果您在循环中等待 30 秒,则它每 30 秒 + 函数执行时间发生一次。只要您的函数调用只需要几毫秒,这与以更复杂的方式进行调用一样精确。
如果你想让你的循环继续运行但你不想启动一个新的Thread
,你可以使用the current Time :
long lastCall = 0;
while(bla) {
if(System.currentTimeMillis() - lastCall > 30000) {
lastCall = System.currentTimeMillis();
callTheFunction();
}
}
关于Java 每隔几秒从循环中执行一次方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23013560/