ThreadLocal,线程变量,是一个以ThreadLocal对象为键、任意对象为值的存储结构。这个结构被附带在线程上,也就是说一个线程可以根据一个ThreadLocal对象查询到绑定在这个线程上的一个值。例如:

 1 class Profiler{
 2     //第一次get()方法调用时会进行初始化(如果set方法没有调用),每个线程会调用一次
 3     private static final ThreadLocal<Long> TIME_THREADLOCAL = new ThreadLocal<Long>(){
 4         protected Long initialValue(){
 5             return System.currentTimeMillis();
 6         }
 7     };
 8     public static final void begin(){
 9         TIME_THREADLOCAL.set(System.currentTimeMillis());
10     }
11     public static final long end(){
12         return System.currentTimeMillis() - TIME_THREADLOCAL.get();
13     }
14     public static void main(String[] args) throws Exception{
15         Profiler.begin();
16         TimeUnit.SECONDS.sleep(1);
17         System.out.println("Cost: " + Profiler.end() + " mills");
18     }
19 }

Profiler可以用来计算方法的耗时,在方法之前调用begin,方法之后调用end。好处是两个方法的调用不用在一个方法或者类中。

posted on 2017-11-26 22:49  飞奔的菜鸟  阅读(167)  评论(0编辑  收藏  举报