Java:实现代码执行中的周期性中断

时间:2017-01-04 08:41:04

标签: java sleep

请建议以下伪代码的最佳实现:

"每10分钟后中断您的业务逻辑并进入睡眠状态5分钟"

2 个答案:

答案 0 :(得分:0)

解决方案

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);
}

请注意,这取决于/* execute stuff */是否可以分解为单个迭代,每个迭代的预期持续时间都比executionDuration更短(希望更短)。

背景

理想的方法是使用守护程序线程,该守护程序线程每10分钟Thread#suspend业务逻辑线程,然后在5分钟后Thread#resume。像这样:

final long executionTimeSlice = 10 * 60 * 1_000;  // in milliseconds
final long suspendedDuration = 5 * 60 * 1_000;  // in milliseconds
final Thread businessThread = Thread.currentThread();

Thread timerThread = new Thread(() -> {
        while (true) {
            businessThread.suspend();
            Thread.sleep(suspendedDuration);

            businessThread.resume();
            Thread.sleep(executionTimeSlice);
        }
});
timerThread.setDaemon(true);
timerThread.start();

不幸的是,Thread#suspend()Thread#resume()都已弃用。正如Oracle的this official statement所示,

  

我应该使用什么而不是Thread.suspendThread.resume

     

......谨慎的做法是让“目标线程”轮询一个变量   指示所需的线程状态(活动或挂起)。当所需状态暂停时,线程等待......

答案 1 :(得分:0)

您可以在无限循环内的子循环中执行逻辑。并在子循环中断条件中使用您的工作时间值:

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
    }
}