上文中使用一个hashmap 来实现线程间的数据共享其实jdk 已经实现了一个这样的类ThreadLocal
于是上节中的代码可以改成这样
public class ThreadScopShareData {
public static int data=0;
static ThreadLocal<Integer> map=new ThreadLocal<Integer>();
public static void main(String[] args){
for (int i=0;i<2;i++)
new Thread(new Runnable() {
public void run() {
data=new Random().nextInt();
map.set(data);
System.out.println(Thread.currentThread().getName()+" has put data: "+data);
new A().get();
new B().get();
}
}).start();
}
static class A{
public int get(){
System.out.println(Thread.currentThread().getName()+" has A get data: "+map.get());
return map.get();
}
}
static class B{
public int get(){
System.out.println(Thread.currentThread().getName()+" has B get data: "+map.get());
return map.get();
}
}
}
Thread-0 has put data: -1169176914
Thread-1 has put data: 270415151
Thread-0 has A get data: -1169176914
Thread-1 has A get data: 270415151
Thread-1 has B get data: 270415151
Thread-0 has B get data: -1169176914
我们将他重新构造一下
public class ThreadScopShareDataThreadLocal {
public static void main(String[] args){
for (int i=0;i<2;i++)
new Thread(new Runnable() {
public void run() {
Data data=Data.getInstance();
data.setAge(new Random().nextInt());
data.setName(Thread.currentThread().getName());
System.out.println(Thread.currentThread().getName()+" has put data: "+data.toString());
new A().get();
new B().get();
}
}).start();
}
static class A{
public void get(){
System.out.println(Thread.currentThread().getName()+" has A get data: "+Data.getInstance().toString());
}
}
static class B{
public void get(){
System.out.println(Thread.currentThread().getName()+" has B get data: "+Data.getInstance().toString());
}
}
}
class Data{
private Data(){};
public static synchronized Data getInstance(){
Data instance=map.get();
if(instance==null){
instance =new Data();
map.set(instance);
}
return instance;
}
// private static Data instance =null;
private static ThreadLocal<Data> map=new ThreadLocal<Data>();
private String name ;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Data{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
文章地址:http://www.haha174.top/article/details/251958
项目源码:https://github.com/haha174/thread-learning.git