使用ThreadLocal能实现线程级别的变量定义,同一个类的私有静态变量,在不同的线程中值可以不同。
1、学习文章:http://blog.csdn.net/qjyong/article/details/2158097
2、示例:http://yulon.iteye.com/blog/549492
3、个人附加:在2的示例中,
如果
(1)在MySession类中加一个方法
public static void printThreadLocal(){
System.out.println("threadLocal object is :"+threadLocal);
}
(2)在main()方法里tx.commit();以后调用MySession.printThreadLocal();
会发现,
三次循环打印出来的threadLocal Object是同一个。这不但证明了“如果我们不使用threadLocal,那么三次
打印的结果中MyTransaction也是同一个对象”,而且告诉了我们如何使用ThreadLocal。