我正在寻找有关在 sleep 中更改线程 sleep 模式的信息。基本上这是我的情况...
public void run() {
while(running) {
//Update Stuff...
try {
long time = System.currentTimeMillis() + interval;
String dateFormatted = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss a").format(new Date(time));
Thread.sleep(interval);
} catch (InterruptedException e) {
//Handle Errors...
}
}
}
所以我正在做的是在程序启动时,它将需要间隔(当前为 60000),但是 GUI 具有能够更改间隔的选项(例如 1 小时、2 小时、3 等)。我可以从 GUI 很好地更新并更改间隔变量。
但是,当我更改它时,线程仍在 sleep 状态,并将等待其完成,并在下一次迭代时更新。中断当前 sleep 线程(或唤醒它?)的最佳方法是什么。另外,我担心它是否“安全”,因为它将在生产服务器上运行。
任何方向/指导都很棒。
最佳答案
您可以通过wait
/notify
实现一个简单的解决方案。
类似这样的事情:
class DurationSleeper {
private final Object monitor = new Object();
private long durationMillis = 0;
public DurationSleeper(long duration, TimeUnit timeUnit) {
setDuration(duration, timeUnit);
}
public void sleep() {
long millisSlept = 0;
while (true) {
synchronized (monitor) {
try {
long millisToSleep = durationMillis - millisSlept;
if (millisToSleep <= 0) {
return;
}
long sleepStartedInNanos = System.nanoTime(); // Not using System.currentTimeMillis - it depends on OS time, and may be changed at any moment (e.g. by daylight saving time)
monitor.wait(millisToSleep);
millisSlept += TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - sleepStartedInNanos);
} catch (InterruptedException e) {
throw new RuntimeException("Execution interrupted.", e);
}
}
}
}
public void setDuration(long newDuration, TimeUnit timeUnit) {
synchronized (monitor) {
this.durationMillis = timeUnit.toMillis(newDuration);
monitor.notifyAll();
}
}
}
关于java - 如何更改已 hibernate 的 Thread.sleep() 的持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31032636/