2.1、StopWatch 启动与停止(ok)

run 方法第第一步就是 创建一个StopWatch,然后启动

public ConfigurableApplicationContext run(String... args) {
	// 1、
	StopWatch stopWatch = new StopWatch();
	stopWatch.start();
	// 略 ...
}

1、new StopWatch()

/****** org.springframework.util.StopWatch ******/

public StopWatch() {
	this("");
}
private final String id;// 唯一标识
public StopWatch(String id) {
	this.id = id;
}

简单不赘述

2、stopWatch.start()

开始计时

/****** org.springframework.util.StopWatch ******/

public void start() throws IllegalStateException {
	start("");
}
private boolean running;// 是否正在运行
private String currentTaskName;// 当前任务名称
private long startTimeMillis;// 当前任务开始时间
public void start(String taskName) throws IllegalStateException {
	if (this.running) {
		throw new IllegalStateException("Can't start StopWatch: it's already running");
	}
	this.running = true;
	this.currentTaskName = taskName;
	this.startTimeMillis = System.currentTimeMillis();
}

简单不赘述

3、stopWatch.stop()

/****** org.springframework.util.StopWatch ******/

private long totalTimeMillis;// 累计耗时
private boolean keepTaskList = true;
private final List<TaskInfo> taskList = new LinkedList<TaskInfo>();
private int taskCount; // 任务计数器
public void stop() throws IllegalStateException {
	if (!this.running) {
		throw new IllegalStateException("Can't stop StopWatch: it's not running");
	}
	long lastTime = System.currentTimeMillis() - this.startTimeMillis;
	this.totalTimeMillis += lastTime;
	this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime);
	if (this.keepTaskList) {
		this.taskList.add(lastTaskInfo);
	}
	++this.taskCount;
	this.running = false;// 设置运行状态为停止
	this.currentTaskName = null;
}


/****** org.springframework.util.StopWatch$TaskInfo  ******/

public static final class TaskInfo {
	private final String taskName;
	private final long timeMillis;
	TaskInfo(String taskName, long timeMillis) {
		this.taskName = taskName;
		this.timeMillis = timeMillis;
	}
}

简单不赘述

整个代码很简单,StopWatch就是一个码表,可以反复启动停止。

停止时会将记录运行时间,然后创建一个任务(TaskInfo)放入码表的List属性中。

Q&A

Q1、run 方法中这个 StopWatch 的作用是什么?

我们看到第 13 步 ,用到了StopWatch 对象,具体作用参考 StartupInfoLogger.logStarted

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java硕哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值