在Java中實(shí)現(xiàn)計(jì)時(shí)功能可以使用System.currentTimeMillis()方法來(lái)獲取當(dāng)前時(shí)間的毫秒數(shù)??梢酝ㄟ^(guò)記錄開(kāi)始時(shí)間和結(jié)束時(shí)間,然后計(jì)算時(shí)間差來(lái)實(shí)現(xiàn)計(jì)時(shí)。
下面是一個(gè)簡(jiǎn)單的示例代碼:
public class TimerExample {
public static void main(String[] args) throws InterruptedException {
long startTime = System.currentTimeMillis();
// 模擬耗時(shí)操作
Thread.sleep(2000);
long endTime = System.currentTimeMillis();
long elapsedTime = endTime - startTime;
System.out.println("耗時(shí):" + elapsedTime + "毫秒");
}
}
在上面的示例中,通過(guò)調(diào)用System.currentTimeMillis()方法獲取開(kāi)始時(shí)間和結(jié)束時(shí)間,然后計(jì)算時(shí)間差,最后輸出耗時(shí)。
注意:這種方式只適用于簡(jiǎn)單的計(jì)時(shí)需求,如果需要更高精度的計(jì)時(shí),可以使用System.nanoTime()方法來(lái)獲取納秒級(jí)別的時(shí)間。