public static void main(String[] args) throws InterruptedException {
final long WORKING_TIME = 10 * 60 * 1000;
final long SLEEPING_TIME = 5 * 60 * 1000;
long startTime;
while (true) {
startTime = System.currentTimeMillis();
while (System.currentTimeMillis() < startTime + WORKING_TIME) {
System.out.println("working..."); // implement your logic here
}
Thread.sleep(SLEEPING_TIME); // sleeping for SLEEPING_TIME
}
}
# 2 楼答案
解决方案
final long executionTimeSlice = 10 * 60 * 1_000_000_000; // in nanoseconds
final long sleepDuration = 5 * 60 * 1_000; // in milliseconds
while (true) {
long endTime = System.nanoTime() + executionTimeSlice;
while (System.nanoTime() < endTime) {
/* execute stuff */
}
Thread.sleep(sleepDuration);
}
What should I use instead of Thread.suspend and Thread.resume?
...the prudent approach is to have the "target thread" poll a variable
indicating the desired state of the thread (active or suspended). When the desired state is suspended, the thread waits...
# 1 楼答案
您可以在无限循环内的子循环中执行逻辑。并在子循环中断条件下使用您的工作时间值:
# 2 楼答案
解决方案
请注意,这取决于
/* execute stuff */
能否被分解为单独的迭代,每个迭代的预期持续时间都比executionDuration
短(希望短得多)背景
理想的方法是使用一个守护进程线程,每10分钟
Thread#suspend
运行一次业务逻辑线程,然后在5分钟后Thread#resume
运行它。比如:不幸的是,^{} 和^{} 都被弃用。正如甲骨文所指出的