温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java多线程如何计时

发布时间:2026-10-03 11:29:49 来源:亿速云 阅读:88 作者:小樊 栏目:编程语言

在 Java 多线程环境下“计时”通常指测量某段代码/任务的执行时间,或在多线程中控制超时/周期执行。下面按常见场景给你总结和示例。


一、测量多线程任务执行时间(最常用)

✅ 方式 1:System.nanoTime()(推荐)

适合计算耗时,不受系统时间修改影响。

long start = System.nanoTime();

// 多线程任务
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.invokeAll(tasks);
executor.shutdown();

long end = System.nanoTime();
System.out.println("耗时:" + (end - start) / 1_000_000 + " ms");

✅ 方式 2:System.currentTimeMillis()

精度较低,但可读性好。

long start = System.currentTimeMillis();
// 任务
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start) + " ms");

二、线程池任务统一计时(等待所有线程完成)

ExecutorService pool = Executors.newFixedThreadPool(5);
List<Callable<Void>> tasks = List.of(
    () -> { Thread.sleep(1000); return null; },
    () -> { Thread.sleep(500); return null; }
);

long start = System.nanoTime();
pool.invokeAll(tasks);
pool.shutdown();
long cost = System.nanoTime() - start;

三、多线程中给单个任务计时(超时控制)

✅ Future.get(timeout)

ExecutorService pool = Executors.newSingleThreadExecutor();
Future<?> future = pool.submit(() -> {
    Thread.sleep(3000);
});

try {
    future.get(2, TimeUnit.SECONDS);
} catch (TimeoutException e) {
    System.out.println("任务超时");
}

四、定时 / 周期性执行(多线程计时器)

✅ ScheduledExecutorService

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);

scheduler.scheduleAtFixedRate(() -> {
    System.out.println("每 1 秒执行");
}, 0, 1, TimeUnit.SECONDS);

五、每个线程自己计时(日志/监控)

Runnable task = () -> {
    long start = System.nanoTime();
    // 业务
    long cost = System.nanoTime() - start;
    System.out.println(Thread.currentThread().getName() + " 耗时:" + cost / 1_000_000 + "ms");
};

六、常见坑提醒 ⚠️

  • ❌ 不要用 Date / Calendar 算耗时
  • ❌ currentTimeMillis() 会被系统时间调整影响
  • ✅ 多线程计时优先用 nanoTime()
  • ✅ 线程池任务用 invokeAll 或 CountDownLatch 等同步后再计时

如果你有具体场景(比如:限时速算、压测、批量任务、Web 接口超时),可以告诉我,我给你更合适的方案。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手