为什么 ScheduledExecutorService 没有按预期工作?

Why is the ScheduledExecutorService not working as expected?

我正在创建一个包含 10 个线程的池 每个线程运行 3 秒 我把每个任务的启动周期设置为0.5秒

问题是,如果池中有10个线程,启动周期为0.5秒,为什么从第一个线程开始到第二个线程需要3秒? 毕竟,10个线程应该在0.5秒内一次启动,以此类推。

如果我使用 newSingleThreadScheduledExecutor 是可以理解的,但我使用的是 newScheduledThreadPool 和 10 个线程。

public class Main17 {

    public static void main(String[] args) {

        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
        Runnable r = ()-> {
            System.out.println("hello "+System.currentTimeMillis());
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        scheduledExecutorService.scheduleAtFixedRate(r,0, 500, TimeUnit.MILLISECONDS);

    }
}

结果

hello 1646991199804
hello 1646991202816     // Interval greater than 0.5 seconds
hello 1646991205831
hello 1646991208840
hello 1646991211850

线程在这里没有作用。您必须了解您使用的方法的效果。

scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) 的文档:

Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor.

重要部分:

If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.

执行器等待 500ms 的间隔或 运行nable 的执行时间,以较长者为准。在您的情况下,是 运行 启用 运行 的时间,因此时间戳的差异正好是 3 秒。

编辑: 你可以看看 ,那里有人遇到了同样的问题。有两个答案可以达到您想要的结果。

引用ScheduledExecutorService.scheduleAtFixedRate()的官方文档:

If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.

来源:ScheduledExecutorService documentation

查看 scheduleAtFixedRate jdk 文档

Blockquote If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute. Blockquote

您的任务至少需要 3 秒才能完成。