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

nbysray5  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(268)

请建议以下伪代码的最佳实现:
“每10分钟中断一次业务逻辑,然后睡5分钟”

wmvff8tz

wmvff8tz1#

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

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

cotxawn72#

解决方案

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 .

背景

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

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() 已弃用。正如甲骨文的官方声明所指出的,
我应该用什么来代替 Thread.suspend 以及 Thread.resume ?
…谨慎的方法是让“目标线程”轮询一个表示线程所需状态(活动或挂起)的变量。当所需状态被挂起时,线程将等待。。。

相关问题