package com.tarena.day21;
import java.util.Random;
public class ThreadLocalTest {
private static ThreadLocal<Integer> x = new ThreadLocal<Integer>();
private static ThreadLocal<MyThreadScopeData> myThreadScopeData = new ThreadLocal<MyThreadScopeData>();
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();
x.set(data);
System.out.println(Thread.currentThread().getName()
+ " put data " + data);
MyThreadScopeData threadScopeData = MyThreadScopeData.getThreadInstance();
threadScopeData.setName("name-" + data);
threadScopeData.setAge(data);
myThreadScopeData.set(threadScopeData);
new A().get();
new B().get();
}
}).start();
}
}
public static class A {
public void get() {
System.out.println("A from " + Thread.currentThread().getName()
+ "get data " + x.get());
MyThreadScopeData threadScopeData = MyThreadScopeData.getThreadInstance();
System.out.println("A from " + Thread.currentThread().getName() + " get threadscope data "+ threadScopeData.getName() + "-" +
threadScopeData.getAge());
}
}
public static class B {
public void get() {
System.out.println("B from " + Thread.currentThread().getName()
+ "get data " + x.get());
MyThreadScopeData threadScopeData = MyThreadScopeData.getThreadInstance();
System.out.println("B from " + Thread.currentThread().getName() + " get threadscope data "+ threadScopeData.getName() + "-" +
threadScopeData.getAge());
}
}
}
class MyThreadScopeData {//只能创建一个实例
private MyThreadScopeData(){
}
public static MyThreadScopeData getThreadInstance(){
MyThreadScopeData instance = map.get();
if(instance == null){
instance = new MyThreadScopeData();
map.set(instance);//创建并保存一个实例对象。
}
return instance;
}
// private static MyThreadScopeData instance = null/*new MyThreadScopeData()*/;
private static ThreadLocal<MyThreadScopeData> map = new ThreadLocal<MyThreadScopeData>();
private String name;
private int age;
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;
}
}