Java中测量时间间隔的一个简单方法

使用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( ) + "
");
 9          Thread.sleep(1000*3);//sleep()使当前线程进入停滞状态(阻塞当前线程),可以使程序休眠一定的时间,这里休眠3秒
10          System.out.println("end time: "+new Date( ) + "
");
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 }

以上代码执行结果如下:

原文地址:https://www.cnblogs.com/liesun/p/7495138.html