ThreadLocal用于保存线程独有变量,结构为以ThreadLocal为键,任意对象为值。
下面例子中,Profiler类通过使用ThreadLocal,计算调用时间消耗(从begin方法到end方法)。Profiler类的优点是两个静态方法begin和end的调用不用在同一个方法或类中。
package com.threadlocal;
import java.util.concurrent.TimeUnit;
public class Profiler {
private static final ThreadLocal<Long> TIME_THREADLOCAL =
new ThreadLocal<Long>() {
@Override
protected Long initialValue() {
return System.currentTimeMillis();
}
};
public static void main(String[] args) throws InterruptedException {
Profiler.begin();
TimeUnit.SECONDS.sleep(1);
System.out.println("Time cost is: " + Profiler.end() + " mills");
}
public static final void begin() {
TIME_THREADLOCAL.set(System.currentTimeMillis());
}
public static final long end() {
// 时间消耗
return System.currentTimeMillis() - TIME_THREADLOCAL.get();
}
}