使用ThreadLocal存取线程局部变量

创建一个独立的线程:

<!----> 1 public class AnotherThread implements Runnable{
2 public void run(){
3
4 TestThreadLocal ttl = new TestThreadLocal();
5 int number1 = ttl.get();
6
7 System.out.println( " another number1 is " + number1);
8 }
9 }


ThreadLocal的测试类:

<!----> 1 public class TestThreadLocal {
2
3 // The next serial number to be assigned
4 private static int nextSerialNum = 0 ;
5
6 private static ThreadLocal serialNum = new ThreadLocal() {
7 protected synchronized Object initialValue() {
8 return new Integer(nextSerialNum ++ );
9 }
10 };
11
12 public static int get() {
13 return ((Integer) (serialNum.get())).intValue();
14 }
15
16 public static void main(String[] args) {
17 TestThreadLocal ttl = new TestThreadLocal();
18 int number1 = ttl.get();
19
20 System.out.println( " number1 is " + number1);
21
22 int number2 = ttl.get();
23
24 System.out.println( " number2 is " + number2);
25
26 new Thread( new AnotherThread()).start();
27 new Thread( new AnotherThread()).start();
28 }
29 }
30

输出结果为:
number1 is 0
number2 is 0
another number1 is 1
another number1 is 2
由此可见,对于同一个线程,都维护一个自己的局部变量。这在并发环境中可以很好的防止线程间共享资源的冲突。ThreadLocal 实例通常是类中的私有静态字段,它们希望将状态与某一个线程(例如,用户 ID 或事务 ID)相关联。

Hibernate中对session的管理有这样一个应用ThreadLocal的实例:
http://www.hibernate.org/207.html

你可能感兴趣的:(thread,html,Hibernate)