爪哇(Java)本身并没有内置的秒表类或功能,但你可以很容易地使用Java的System.currentTimeMillis()
方法或java.time
包中的类来实现一个简单的秒表功能。
以下是一个简单的秒表实现示例:
import java.time.Duration;
import java.time.Instant;
public class Stopwatch {
private Instant startTime;
private Instant stopTime;
public void start() {
startTime = Instant.now();
}
public void stop() {
stopTime = Instant.now();
}
public long getElapsedTime() {
if (startTime == null || stopTime == null) {
throw new IllegalStateException("秒表未启动或未停止");
}
return Duration.between(startTime, stopTime).toMillis();
}
public static void main(String[] args) throws InterruptedException {
Stopwatch stopwatch = new Stopwatch();
stopwatch.start();
Thread.sleep(2000); // 模拟一些操作
stopwatch.stop();
System.out.println("经过的时间: " + stopwatch.getElapsedTime() + "毫秒");
}
}
System.currentTimeMillis()
的精度可能受到系统时钟的影响。如果需要更高的精度,可以考虑使用System.nanoTime()
。synchronized
关键字或java.util.concurrent
包中的工具来解决这个问题。希望这个答案能帮到你!如果你有其他关于Java或其他技术的问题,欢迎随时提问。
没有搜到相关的文章