注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

love3400wind的blog

like

 
 
 

日志

 
 
 
 

ThreadLocal最佳实践 servlet 线程对应的容器  

2015-10-24 16:26:57|  分类: 默认分类 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

package threadLocal;

import java.util.Random;

public class ThreadLocalScopeShareBeanData {
private static final ThreadLocal<Integer> myData = new ThreadLocal<Integer>();

/**
* @param args
*/
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {

@Override
public void run() {
int data = new Random().nextInt();
myData.set(data);
Business business = Business.getInstance();
business.setAge(data);
business.setName("myName" + data);

System.out.println(Thread.currentThread().getName()
+ " load data: " + data);
System.out.println(Thread.currentThread().getName() + "load business data: " + data);
new A().print();
new B().print();
}
}).start();
}
}

static class A {
public void print() {
int data = myData.get();
Business business = Business.getInstance();
System.out.println("A from " + Thread.currentThread().getName()
+ ", data " + data);
System.out.println("A from " + Thread.currentThread().getName()
+ ", business name: " + business.getName() + ", age: "
+ business.getAge());
}
}

static class B {
public void print() {
int data = myData.get();
Business business = Business.getInstance();
System.out.println("B from " + Thread.currentThread().getName()
+ ", data " + data);
System.out.println("B from " + Thread.currentThread().getName()
+ ", business name: " + business.getName() + ", age: "
+ business.getAge());
}
}



}

class Business {
private static ThreadLocal<Business> data = new ThreadLocal<Business>();
private Business(){}
public static /*synchronized*/ Business getInstance(){
business = data.get();
if (business == null) {
business = new Business();
data.set(business);
}

return business;
}
private static Business business;// = new Business();

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

private String name;

private int age;
}



  评论这张
 
阅读(102)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017