-------
android培训、
java培训、期待与您交流! ----------
public class ThreadLocalDemo {
/**
* ThreadLocal类的使用。
* 我们在做线程范围内的变量共享的时候。其实是定义了一个map集合
* 把我们要在线程上共享的数据和当前的线程进行了绑定。是以当前的线程
* 做为key,要绑定的数据做为值存储到map集合中的。我们在线程中所要调用的
* 模块中取得线程所共享的数据。是使用的当前的线程进行取的。
* 通过以上的方式来实现线程范围内的数据共享的。
*
* 其实在jdk中为我们提供了一个api,这个api就是ThreadLocal这个类
* 其实它就相当于是一个map的存在。
* 我们来对我们的的代码进行改写
*
Thread-0 has put data :-1490623450
Thread-1 has put data :-502973024
ModuleA from:Thread-1 get data :-502973024
ModuleA from:Thread-0 get data :-1490623450
ModuleB from:Thread-0 get data :0
ModuleB from:Thread-1 get data :0
线程上的数据被第一个模块取走了。所以第二个模块再去取就没有了。
是因为我们的第二个模块的获取数据的代码没有写
Thread-0 has put data :-1949375047
Thread-1 has put data :-1149866833
ModuleA from:Thread-1 get data :-1149866833
ModuleA from:Thread-0 get data :-1949375047
ModuleB from:Thread-0 get data :-1949375047
ModuleB from:Thread-1 get data :-1149866833
*/
// private static int data = 0;
// 我们要实现范围内的数据共享
// 即线程上的所有的模块使用的对象都是同一个
// 我们可以使用map集合来实现,把线程和数据给封装成EntrySet对象。填充到 map集合中
// private static Map<Thread, Integer> threadData = new HashMap<Thread, Integer>();
//使用ThreadLocal改写
private static ThreadLocal<Integer> x=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();
System.out.println(Thread.currentThread().getName()
+ " has put data :" + data);
// 把当前的线程和要做为在当前线程内共享的数据添加到map集合中
//把当前的线程做为key,把共享的数据做为value添加到map集合中
// threadData.put(Thread.currentThread(), data);
x.set(data); //我们是直接把做为线程上共享的数据设置上当前线程上去的。
//这和我们上面的操作是不一样的。
new ModuleA().getData();
new ModuleB().getData();
}
}).start();
}
}
static class ModuleA {
public void getData() {
//从集合中获取数据
//集合中存放的是其实是当前线程和在线程上所共享的数据
// int data=threadData.get(Thread.currentThread());
//从ThreadLocal中取出当前线程上的数据
int data=x.get();
System.out.println("ModuleA from:"
+ Thread.currentThread().getName() + " get data :" + data);
}
}
static class ModuleB {
public void getData() {
// int data=threadData.get(Thread.currentThread());
//从ThreadLocal中取出当前线程上的数据
int data=x.get();
System.out.println("ModuleB from:"
+ Thread.currentThread().getName() + " get data :" + data);
}
}
}