5.线程范围内共享变量的概念与作用

 1 import java.util.HashMap;
 2 import java.util.Map;
 3 import java.util.Random;
 4 
 5 /*******************************
 6  * 模拟ThrealLocal的实现
 7  * 用处:
 8  *  用在数据库操作中俄beginTransaction -> commit
 9  *  在Hibernate中也是使用它来保证在多线程下Session自己不冲突。
10  *     OpenSessionInView模式
11  *        spring的OpenSessionInView也是使用ThreadLocal来实现, OpenSessionInViewFilter过滤器
12  *        当请求到底是打开一个session,请求结束时关闭。
13  *        缺陷就是如果客户端的网速慢,会导致数据库的链接一直被占用。
14  *    扩展:OpenSessionInView模式用AOP替代
15  * *****************************
16  * @author LiTaiQing
17  */
18 public class ThreadScopeShareData {
19     private static Map<Thread,Integer> threadData = new HashMap<Thread,Integer>();
20     public static void main(String[] args){
21         for(int i = 0; i < 10 ; i++){
22             new Thread(new Runnable(){
23                 @Override
24                 public void run() {
25                     int data = new Random().nextInt();
26                     System.out.println(Thread.currentThread().getName() + " get put data :" + data);
27                     threadData.put(Thread.currentThread(), data);
28                     new A().get();
29                     new B().get();
30                 }
31             }).start();
32         }
33     }
34     static class A{
35         public void get(){
36             int data = threadData.get(Thread.currentThread());
37             System.out.println("A from" + Thread.currentThread().getName() + " get put data :" + data);
38         }
39     }
40     static class B{
41         public void get(){
42             int data = threadData.get(Thread.currentThread());
43             System.out.println("B from" + Thread.currentThread().getName() + " get put data :" + data);
44         }
45     }
原文地址:https://www.cnblogs.com/litaiqing/p/4635192.html