import java.time.Duration;
import java.time.Instant;
public class Stopwatch {
private Instant startTime;
private Instant endTime;
private boolean running;
public Stopwatch() {
this.running = false;
}
// 开始计时
public void start() {
if (running) {
throw new IllegalStateException("Stopwatch is already running");
}
startTime = Instant.now();
running = true;
}
// 停止计时
public void stop() {
if (!running) {
throw new IllegalStateException("Stopwatch is not running");
}
endTime = Instant.now();
running = false;
}
// 获取经过的时间(以秒为单位)
public double getElapsedTime() {
if (running) {
throw new IllegalStateException("Stopwatch is still running");
}
return Duration.between(startTime, endTime).getSeconds();
}
// 获取经过的时间(以毫秒为单位)
public long getElapsedTimeMillis() {
if (running) {
throw new IllegalStateException("Stopwatch is still running");
}
return Duration.between(startTime, endTime).toMillis();
}
public static void main(String[] args) {
Stopwatch stopwatch = new Stopwatch();
// 开始计时
stopwatch.start();
// 模拟一些耗时操作
try {
Thread.sleep(2000); // 睡眠2秒
} catch (InterruptedException e) {
e.printStackTrace();
}
// 停止计时
stopwatch.stop();
// 输出经过的时间
System.out.println("Elapsed time in seconds: " + stopwatch.getElapsedTime());
System.out.println("Elapsed time in milliseconds: " + stopwatch.getElapsedTimeMillis());
}
}
Stopwatch
类用于实现一个简单的计时器功能。startTime
和 endTime
:分别记录开始时间和结束时间,使用 Instant
类表示。running
:布尔值,用于标记计时器是否正在运行。start()
:开始计时,记录当前时间为 startTime
。stop()
:停止计时,记录当前时间为 endTime
。getElapsedTime()
:返回经过的时间(以秒为单位)。getElapsedTimeMillis()
:返回经过的时间(以毫秒为单位)。main
方法中创建了一个 Stopwatch
对象,模拟了一个耗时操作(线程睡眠2秒),然后输出经过的时间。上一篇:java生成唯一id
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站