工具类-耗时计算工具类TimeCostUtil基于ThreadLocal实现
功能:基于ThreadLocal实现,可在线程内任意地方开始计时、计算计时和终止计时;
/**
* 耗时计算工具类
*
* @Author ccl
* @Date 2020/12/28 14:08
*/
public class TimeCostUtil {
private static final ThreadLocal<Long> TIME_THREADLOCAL = new ThreadLocal<Long>() {
@Override
protected Long initialValue() {
return System.currentTimeMillis();
}
};
/**
* 开始计时
*/
public static void begin() {
long l = System.currentTimeMillis();
TIME_THREADLOCAL.set(l);
}
/**
* 结束计时
*
* @return
*/
public static long end() {
long cost = System.currentTimeMillis() - TIME_THREADLOCAL.get();
TIME_THREADLOCAL.remove();
return cost;
}
/**
* 获取开始时间
*
* @return
*/
public static long get() {
return TIME_THREADLOCAL.get();
}
/* public static void main(String[] args) {
System.out.println(TimeCostUtil.end());
new Thread(()->{
System.out.println(TimeCostUtil.end());
}).start();
new Thread(()->{
System.out.println(TimeCostUtil.end());
}).start();
}*/
}