文章目录
ThreadLocal,即线程变量,是一个以ThreadLocal对象为键、任意对象为值的存储结构。
这个结构附带在线程上,也就是说一个线程可以根据一个ThreadLocal对象查询到绑定在这个线程上的一个值。
通过set(T)方法设置一个值,在当前线程下再通过get()方法获取到原先设置的值
例子:
构建了一个常用的Profiler类,具有begin和end两个方法,end()方法返回从begin()方法调用到end()方法调用时的时间差,单位是毫秒。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public class Profiler { private static final ThreadLocal<Long> TIME_THREADLOCAL = new ThreadLocal<Long>(){ protected Long initialValue(){ return System.currentTimeMillis(); } };
public static final void begin(){ TIME_THREADLOCAL.set(System.currentTimeMillis()); }
public static final Long end(){ return System.currentTimeMillis() - TIME_THREADLOCAL.get(); }
public static void main(String[] args) throws InterruptedException { Profiler.begin(); TimeUnit.SECONDS.sleep(3); System.out.println("Cost:" + Profiler.end() + "mills"); } }
|