import java.util.Random;
public class ThreadDemo3 {
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();
data1.getIntance().setName("fdf"+data);
data1.getIntance().setAge(data);
System.out.println(Thread.currentThread().getName() + " data:" + data);
System.out.println(Thread.currentThread().getName() + " hashcode "+data1.getIntance().getClass().hashCode());
new a().get();
new b().get();
}
}).start();
}
}
static class a {
public void get() {
int data=data1.getIntance().getAge();
System.out.println(Thread.currentThread().getName() + " a data:" + data);
}
}
static class b {
public void get() {
int data=data1.getIntance().getAge();
System.out.println(Thread.currentThread().getName() + " b data:" + data);
}
}
}
class data1{
private String name;
private int age;
private static ThreadLocal<data1> mapdata=new ThreadLocal<data1>();
private data1(){}
public static data1 getIntance(){
data1 da=mapdata.get();
if(da==null)
{
da=new data1();
mapdata.set(da);
}
return da;
}
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;
}
}