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
}
}
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);
}
2条答案
按热度按时间wmvff8tz1#
您可以在无限循环内的子循环中执行逻辑。并使用子循环中断条件下的工作时间值:
cotxawn72#
解决方案
请注意,这取决于
/* execute stuff */
能够被分解成单独的迭代,每个迭代的预期持续时间比executionDuration
.背景
理想的方法是使用一个守护进程线程
Thread#suspend
业务逻辑线程每10分钟一次,然后Thread#resume
5分钟后。像这样:不幸的是,两者
Thread#suspend()
以及Thread#resume()
已弃用。正如甲骨文的官方声明所指出的,我应该用什么来代替
Thread.suspend
以及Thread.resume
?…谨慎的方法是让“目标线程”轮询一个表示线程所需状态(活动或挂起)的变量。当所需状态被挂起时,线程将等待。。。