有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (2) 个答案

  1. # 1 楼答案

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

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

    请注意,这取决于/* 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();
    

    不幸的是,^{}^{}都被弃用。正如甲骨文所指出的

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