这是我的代码
while (true) {
try {
Thread.sleep(5 * 60 * 1000);
processData();// data processing job
} catch (InterruptedException e) {
SystemMessageBillPay.getInstance().writeMessage("ERROR: CEB.run() - " + e.getMessage());
} catch (NumberFormatException e) {
SystemMessageBillPay.getInstance().writeMessage("ERROR: CEB.run() - " + e.getMessage());
}
}
为此
"Thread.sleep(5 * 60 * 1000);"
代码检查器发出警告
"Invoking Thread.sleep in loop can cause performance problems"
防止这个警告的代码应该是什么
最佳答案
对于 1.8,您还可以使用:
import java.util.concurrent.locks.LockSupport;
LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(1000));
根据 Javadoc:
Disables the current thread for thread scheduling purposes, for up to the specified waiting time, unless the permit is available.
好的部分是,它的签名不会抛出已检查的异常。所以你不必 try catch (不像 Thread.sleep,它需要处理它的 InterruptedException)。当然,各有各的用途。
关于java - Java 中是否有替代 Thread.sleep 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37938676/