package cn.itcast.gz;
import java.util.Random;
public class ThreadLocalTest2 {
public static void main(String[] args) {
for(int i = 0;i<2;i++)
{
new Thread(){
@Override
public void run() {
int value = new Random().nextInt(100);
System.out.println(Thread.currentThread().getName() +"has put "+value);
MyThreadLocalData.getThreadLocalInstance().setName("xiaoming"+value);
MyThreadLocalData.getThreadLocalInstance().setAge(value);
new A();
new B();
}
}.start();
}
}
static class A
{
public A()
{
String name = MyThreadLocalData.getThreadLocalInstance().getName();
Integer age = MyThreadLocalData.getThreadLocalInstance().getAge();
System.out.println(Thread.currentThread().getName()+"name: "+name+" age: "+age);
}
}
static class B
{
public B()
{
String name = MyThreadLocalData.getThreadLocalInstance().getName();
Integer age = MyThreadLocalData.getThreadLocalInstance().getAge();
System.out.println(Thread.currentThread().getName()+"name: "+name+" age: "+age);
}
}
}
class MyThreadLocalData
{
private MyThreadLocalData(){}
private static ThreadLocal<MyThreadLocalData> data = new ThreadLocal<MyThreadLocalData>();
public static MyThreadLocalData getThreadLocalInstance()
{
MyThreadLocalData instance = data.get();
if(instance==null)
{
instance = new MyThreadLocalData();
data.set(instance);
}
return instance;
}
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}