在 Java 多线程环境下“计时”通常指测量某段代码/任务的执行时间,或在多线程中控制超时/周期执行。下面按常见场景给你总结和示例。
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");
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("任务超时");
}
ScheduledExecutorServiceScheduledExecutorService 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 接口超时),可以告诉我,我给你更合适的方案。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。