首页 > 编程语言 > 详细

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

时间:2015-07-10 12:57:07      阅读:134      评论:0      收藏:0      [点我收藏+]
 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     }

 

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

原文:http://www.cnblogs.com/litaiqing/p/4635192.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!