阻塞时间超过其 运行 间隔的 ScheduledExecutorService 任务

ScheduledExecutorService task that blocks for longer than its run interval

关于 ScheduledExecutorService.shceduleAtFixedRate 的问题 - 我每 500 毫秒将 taskA 安排到 运行,这会阻塞 1000 毫秒。现在后续的执行不会等待额外的 500 毫秒,而是在前一个执行之后立即开始。

taskA 获取一个内部锁,它也被另一个线程(尝试)获取。由于内在锁没有公平性保证,此线程存在 运行 饥饿风险,所以这是我的问题:是否有 good/clean 方法来避免这种风险?例如。将任务安排为每 1500 毫秒 运行(听起来不是很防水)?或者我们是否期望锁获取表现出一种 "amortized fairness"?

是的,您可以使用 scheduleWithFixedDelay:

Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next. 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.

所以你给出的延迟是下一个结束到最后一个结束之间的时间 - 即运行之间没有重叠。