思路:1、启动线程,得到一个伪随机变量
int data = newRandom().nextInt();
map.set(Thread.currentThread(),data);
int data =map.get(Thread.currentThread());
System.out.println("A thread:"+Thread.currentThread().getName()+
" has get data:"+data);
二、当 有多个变量时,通常有两种方法实现
存入
2、
private staticMap<Thread, Integer> map = newHashMap<Thread,Integer>();
3、得到随机到的变量值
存储结构如下图
1、多次存储
2、封装成对象,再由对象操作。
存入
map.set(Thread.currentThread(),data);
获得
int data =map.get(Thread.currentThread());
使用ThreadLocal可以大大减少复杂程度。
存入
threadLocal.set(data);
获取
int data =threadLocal.get();
为了充分体现面向对象的思想,将ThreadLocal完全封装到一个类中
存入
myThreadScopeData mydata =myThreadScopeData.getThreadInstance();
mydata.setName("name"+data);
mydata.setAge(data);
new A().get();
new B().get();
获取
myThreadScopeData myData =myThreadScopeData.getThreadInstance();