JAVA工具类

一、概述

1. 字符串占位符 

复制代码
// 字符串占位
// 方法一:使用String的静态方法format
String format = String.format(" %s * %s = %s", "2", "3", 5);
// 2 * 3 = 5
System.out.println("format: " + format);

// 方法二:功能强大,支持指定类型和格式,性能更好,但是需要指定参数位置
// 参考:https://blog.csdn.net/GarfieldEr007/article/details/89397843
String format1 = MessageFormat.format(" {0} * {1} = {2}", "2", "3", 5);
//  2 * 3 = 5
System.out.println("format1: " + format1);

// 方法三:日志输出中使用占位符
try {
    int a = 2 / 0;
} catch (Exception e) {
    log.info(" {} * {} = {}", "2", "3", 5, e);
}

// 方法四: 没有换行符
// 2 * 3 = 5
System.out.printf(" %s * %s = %s", "2", "3", 5);
System.out.println();
复制代码

 2、StopWatch

2.1 lang3

StopWath是 apache commons lang3 包下的一个任务执行时间监视器,与我们平时常用的秒表的行为比较类似。

依赖:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.6</version>
</dependency>

API:

 

 示例:

 

复制代码
public static void main(String[] args) throws InterruptedException {
    //创建后立即start,常用
    StopWatch watch = StopWatch.createStarted();

    // StopWatch watch = new StopWatch();
    // watch.start();

    Thread.sleep(1000);
    System.out.println(watch.getTime());
    System.out.println("统计从开始到现在运行时间:" + watch.getTime() + "ms");

    Thread.sleep(1000);
    watch.split();
    System.out.println("从start到此刻为止的时间:" + watch.getTime());
    System.out.println("从开始到第一个切入点运行时间:" + watch.getSplitTime());


    Thread.sleep(1000);
    watch.split();
    System.out.println("从开始到第二个切入点运行时间:" + watch.getSplitTime());

    // 复位后, 重新计时
    watch.reset();
    watch.start();
    Thread.sleep(1000);
    System.out.println("重新开始后到当前运行时间是:" + watch.getTime());

    // 暂停 与 恢复
    watch.suspend();
    System.out.println("暂停2秒钟");
    Thread.sleep(2000);

    // 上面suspend,这里要想重新统计,需要恢复一下
    watch.resume();
    System.out.println("恢复后执行的时间是:" + watch.getTime());

    Thread.sleep(1000);
    watch.stop();

    System.out.println("花费的时间》》" + watch.getTime() + "ms");
    // 直接转成s
    System.out.println("花费的时间》》" + watch.getTime(TimeUnit.SECONDS) + "s");
}
View Code
复制代码

 

参考:https://mp.weixin.qq.com/s/SRL94kccWCPTe_NlLj0bRg

 

posted @   一帘幽梦&nn  阅读(154)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击查看具体代码内容
点击右上角即可分享
微信分享提示