StopWath,apache commons lang3 包下的一个使命实验时间监督器的利用

[复制链接]
发表于 2026-1-15 20:09:06 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
StopWath是 apache commons lang3 包下的一个使命实验时间监督器,与我们平经常用的秒表的活动比力雷同,我们先看一下此中的一些告急方法:

  1. <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
  2. <dependency>   
  3.     <groupId>org.apache.commons</groupId>   
  4.     <artifactId>commons-lang3</artifactId>   
  5.     <version>3.6</version>
  6. </dependency>
复制代码
Apache提供的这个使命实验监督器功能丰富强大,机动性强,如下经典实用案例:
  1. public static void main(String[] args) throws InterruptedException {   
  2.     //创建后立即start,常用    
  3.     StopWatch watch = StopWatch.createStarted();
  4.     // StopWatch watch = new StopWatch();   
  5.     // watch.start();    Thread.sleep(1000);   
  6.     System.out.println(watch.getTime());   
  7.     System.out.println("统计从开始到现在运行时间:" + watch.getTime() + "ms");
  8.     Thread.sleep(1000);   
  9.     watch.split();   
  10.     System.out.println("从start到此刻为止的时间:" + watch.getTime());   
  11.      System.out.println("从开始到第一个切入点运行时间:" + watch.getSplitTime());
  12.     Thread.sleep(1000);   
  13.     watch.split();   
  14.     System.out.println("从开始到第二个切入点运行时间:" + watch.getSplitTime());   
  15.     // 复位后, 重新计时   
  16.     watch.reset();   
  17.     watch.start();   
  18.     Thread.sleep(1000);   
  19.     System.out.println("重新开始后到当前运行时间是:" + watch.getTime());   
  20.     // 暂停 与 恢复   
  21.     watch.suspend();   
  22.     System.out.println("暂停2秒钟");   
  23.     Thread.sleep(2000);   
  24.     // 上面suspend,这里要想重新统计,需要恢复一下   
  25.      watch.resume();   
  26.     System.out.println("恢复后执行的时间是:" + watch.getTime());
  27.     Thread.sleep(1000);    
  28.     watch.stop();
  29.     System.out.println("花费的时间》》" + watch.getTime() + "ms");   
  30.     // 直接转成s   
  31.     System.out.println("花费的时间》》" + watch.getTime(TimeUnit.SECONDS) + "s");
  32. }
复制代码

回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表