基于单例使用ThreadLocal对多线程下数据的访问修改

时间:2022-04-03 03:31:51
 package cn.lyy.thread;

 import java.util.Random;

 /**
* 基于单例模式的基础上,使用ThreadLocal为每一个进入的线程生成一个实例,
* 用来对数据的访问修改而不影响到别的线程对同一个数据的修改
* @author Administrator
*
*/
public class ThreadLocalTest { 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(20);
MyThreadScopeData.getThreadInstance().setAddress(
"*daxue" + data);
MyThreadScopeData.getThreadInstance().setAge(data);
new A().get();
new B().get();
}
}).start();
}
} static class A { public void get() {
MyThreadScopeData myData = MyThreadScopeData.getThreadInstance();
System.out.println("A from " + Thread.currentThread().getName()
+ " getMyData: " + myData.getAddress() + ","
+ myData.getAge());
} } static class B { public void get() { MyThreadScopeData myData = MyThreadScopeData.getThreadInstance();
System.out.println("B from " + Thread.currentThread().getName()
+ " getMyData: " + myData.getAddress() + ","
+ myData.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 ThreadLocal<MyThreadScopeData> map = new ThreadLocal<MyThreadScopeData>(); private String address; public String getAddress() {
return address;
} public void setAddress(String address) {
this.address = address;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} private int age;
}