通过调用ThreadLocal来实现线程范围内共享变量
源代码如下:
public class ThreadLocalTest {
private 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(){
int data = new Random().nextInt();
map.set(data);
System.out.println(Thread.currentThread().getName()+" is : "+data);
MyThreadData.getThreadInstance().setData(data);
new A().getDate();
new B().getDate();
}
}).start();
}
}
static class A{
public void getDate(){
int data = map.get();
System.out.println("a from "+Thread.currentThread().getName()+" : "+data);
MyThreadData mydata = MyThreadData.getThreadInstance();
System.out.println("--- a from "+Thread.currentThread().getName()+" : "+mydata.getData());
}
}
static class B{
public void getDate(){
int data = map.get();
System.out.println("b from "+Thread.currentThread().getName()+" : "+data);
MyThreadData mydata = MyThreadData.getThreadInstance();
System.out.println("--- b from "+Thread.currentThread().getName()+" : "+mydata.getData());
}
}
}
//此类方法原理和设计模式中的单例模式一样
class MyThreadData{
private int data;
private static ThreadLocal<MyThreadData> localmap = new ThreadLocal<MyThreadData>();
@SuppressWarnings("unused")
public static MyThreadData getThreadInstance(){
MyThreadData mythread = localmap.get();
if(mythread == null){
mythread = new MyThreadData();
localmap.set(mythread);
}
return mythread;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
}
关于线程范围内共享变量的这两种方法,大家可以去对比下!