ThreadLocal实例

ThreadLocal基于线程的数据存储结构。ThreadLocal是类型于Map的一种数据结构,它以当前线程的ThreadLocal为key,来实现当前线程范围内的局部变量对象的共享。其保存和获取的方法是set(Object)和get()。
应用实例:
/**
* <br>
* do what you want to do and never stop it.
* <br>
*/
package com.luch.thread;

import java.util.Random;

/**
* @author Jack
* Jul 7, 2014
* <br>
*/
public class ThreadScopeShareData {

/**
* @param args
*/
public static void main(String[] args) {
for(int i =0; i < 2; i++) {
new Thread(new Runnable(){
public void run() {
int data = new Random().nextInt();
System.out.println(Thread.currentThread().getName() + " has put count:" +data);
MyThreadScopeData.getInstance().setName("name"+data);
System.out.println(Thread.currentThread().getName() +" MyThreadScopeData: " + MyThreadScopeData.getInstance());
new A().get();
new B().get();
}

}).start();
}
}

static class A{
public void get(){
System.out.println("A " + Thread.currentThread().getName() + " Singlton: " + MyThreadScopeData.getInstance());
System.out.println("A " + Thread.currentThread().getName() + " has get count:" +MyThreadScopeData.getInstance().getName());
}
}

static class B{
public void get(){
System.out.println("B " + Thread.currentThread().getName() + " Singlton: "+MyThreadScopeData.getInstance());
System.out.println("B " + Thread.currentThread().getName() + " has get count:" +MyThreadScopeData.getInstance().getName());
}
}


static class MyThreadScopeData{
private String name;
private int age;
private MyThreadScopeData(){}
//private static volatile MyThreadScopeData instance;

public static /*synchronized*/ MyThreadScopeData getInstance(){
MyThreadScopeData instance = map.get();
if (instance == null) {
instance = new MyThreadScopeData();
map.set(instance);
}
return instance;
}
public static ThreadLocal<MyThreadScopeData> map = new ThreadLocal<MyThreadScopeData>();

public String getName() {
System.out.println("getName:" + Thread.currentThread().getName() + " name=" + name + " this.name=" + this.name + " " + this.toString());
return name;
}
public synchronized void setName(String name) {
this.name = name;
System.out.println("setName:" + Thread.currentThread().getName() + " name=" + name + " this.name=" + this.name + " " + this.toString());
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}

}

此实例就通过ThreadLocal这个对象来达到MyThreadScopeData 实例对象在当前线程范围内(这里是Module A和Module B)共享同一个对象。并且通过单例的模式,很好的屏蔽了ThreadLocal对外部模块的可见性。


Set(T)的源代码如下:
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}

把要保存的对象保存到ThreadLocalMap这个对象中,并且以ThreadLocal本身作为key,如果此Map一开始不存在,就去初始化一个Map,然后保存值Value。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值