当前位置:   article > 正文

2.1、StopWatch 启动与停止(ok)_stopwatch.start

stopwatch.start

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

public ConfigurableApplicationContext run(String... args) {
	// 1、
	StopWatch stopWatch = new StopWatch();
	stopWatch.start();
	// 略 ...
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

1、new StopWatch()

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

public StopWatch() {
	this("");
}
private final String id;// 唯一标识
public StopWatch(String id) {
	this.id = id;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

简单不赘述

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();
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

简单不赘述

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;
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

简单不赘述

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

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

Q&A

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

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/511904
推荐阅读
相关标签
  

闽ICP备14008679号