使用Java測量時間間隔有許多方法,這里寫一個比較簡單的方法。
1 import java.util.*; 2 3 public class DiffDemo { 4 5 public static void main(String args[]) { 6 try { 7 long start = System.currentTimeMillis( );//獲取開始時間,以自1970年1月1日經歷的毫秒數值表示 8 System.out.println("start time: "+new Date( ) + "\n"); 9 Thread.sleep(1000*3);//sleep()使當前線程進入停滯狀態(阻塞當前線程),可以使程序休眠一定的時間,這里休眠3秒 10 System.out.println("end time: "+new Date( ) + "\n"); 11 long end = System.currentTimeMillis( );//獲取結束時間 12 long diff = (end - start)/1000;//轉換為秒數 13 System.out.println("time spand : " + diff); 14 } catch (Exception e) { 15 System.out.println("Got an exception!"); 16 } 17 } 18 }
以上代碼執行結果如下:

