【问题标题】:Does TimeUnit chosen affect precision of Java utility classes?选择的 TimeUnit 是否会影响 Java 实用程序类的精度?
【发布时间】:2025-12-05 21:20:09
【问题描述】:

当我使用具有 TimeUnit.MINUTES 且值为 3 的 ScheduledExecutor 时,作业的执行延迟从 3 分钟到大约 3 分 10 秒不等。是的,我正在使用 scheduleWithFixedDelay(),但作业应该只运行几毫秒。

我没有从 java.util.concurrent 的文档中找到任何明确的迹象表明 TimeUnit.MINUTES * 3 不等于 TimeUnit.SECONDS * 180 但它也使计时不太精确。

在我的情况下,分钟刻度的精度是完全可以接受的。我只是想知道是否有人知道这是否真的是预期的行为,或者我应该担心的事情......

即使我的问题已得到解答,如果有人可能有兴趣对其进行测试,我也会在此处提供一些示例代码:

public static void main(String[] args) {

    ScheduledExecutorService exec = Executors
            .newSingleThreadScheduledExecutor();

    exec.scheduleWithFixedDelay(new UpdateTask(), 0, 3, TimeUnit.MINUTES);

    Scanner sc = new Scanner(System.in);

    boolean quitted = false;
    while (!quitted) {
        String command = sc.nextLine();
        if (command.equals("q"))
            quitted = true;
    }
    exec.shutdown();

}

private static final class UpdateTask implements Runnable {

    @Override
    public void run() {
        System.out.println("bg process running (" + (new Date()) + ")");
    }
}

该代码 sn-p 导致(当在我的系统后台执行各种其他操作时):

bg process running (Thu Oct 18 10:49:48 EEST 2012)
bg process running (Thu Oct 18 10:52:54 EEST 2012)
bg process running (Thu Oct 18 10:55:57 EEST 2012)
bg process running (Thu Oct 18 10:58:59 EEST 2012)
bg process running (Thu Oct 18 11:02:02 EEST 2012)
bg process running (Thu Oct 18 11:05:05 EEST 2012)
bg process running (Thu Oct 18 11:08:07 EEST 2012)

问题不应该是 Quoi 建议的(谢谢),因为我正在运行 Win7,所以它可能与 Win7 线程调度、优先级和我机器上相当重的负载有关。

【问题讨论】:

标签: java precision timeunit


【解决方案1】:

toNanos() 方法由 ScheduledThreadPoolExecutor 使用,以下表达式都计算出完全相同的 180000000000 值:

TimeUnit.MINUTES.toNanos(3)

TimeUnit.SECONDS.toNanos(180)

因此错误一定在其他地方,最有可能在旅游代码中或系统处于高负载状态。

【讨论】:

  • 这绝对回答了这个问题。可能问题是我只是让进程在后台运行的 win 7 笔记本电脑有
  • 抱歉我的编辑时间用完了...我会给你+1,但我没有足够的声誉...可能问题是我刚刚让进程运行win 7 笔记本电脑的背景,同时运行大量程序(86 个进程,1100 个线程)(从一个相当繁重的 eclipse 实例开始)。我最初的任务确实包括一个(几乎肯定是非竞争的)数据库事务,但这似乎是原因,因为我在原始问题中包含的一个简单示例代码得到了相同的行为(不适合这里)。
  • @Riku:没问题,很高兴我能帮上忙。添加一些日志记录/分析以查看运行您的工作实际需要多长时间。当然也可以在闲置的机器上进行测试。
最近更新 更多