最近在网上找了很多有关ThreadLocal的介绍,总之很难理解,以下是我筛选出来比较实用的一段话:
ThreadLocal不是用来解决对象共享访问问题的,而主要是提供了保持对象的方法和避免参数传递的方便的对象访问方式。归纳了两点:
1。每个线程中都有一个自己的ThreadLocalMap类对象,可以将线程自己的对象保持到其中,各管各的,线程可以正确的访问到自己的对象。
2。将一个共用的ThreadLocal静态实例作为key,将不同对象的引用保存到不同线程的ThreadLocalMap中,然后在线程执行的各处通过这个静态ThreadLocal实例的get()方法取得自己线程保存的那个对象,避免了将这个对象作为参数传递的麻烦。
===============================================================
起初我有几点疑问:
(1)ThreadLocal和Thread有什么关系?
(2)ThreadLocalMap和Map有什么区别?
第一个问题:
ThreadLocal和Thread有什么关系?
查询了大量的资料发现两者之间没有直接关系,Thread是线程,而ThreadLocal是线程存储对象的容器。在实际开发中,往往会用到线程来传递一些数据,而ThreadLocal就是传递数据的容器。
下面分别用Map和ThreadLocal传递数据作为对比:
Map:
public class MyThread extends Thread {
private Map<Thread, Integer> mThreadData;
/**
* 构造方法
*
* @param mThreadData 数据
*/
public MyThread(Map<Thread, Integer> mThreadData) {
this.mThreadData = mThreadData;
}
@Override
public void run() {
super.run();
synchronized (this) {
int num = new Random().nextInt(10);
System.out.println(this.getName());
mThreadData.put(this, num);
System.out.println(this.getName() + "---------" + mThreadData.get(this).toString());
}
}
}
public class ThreadLocalDemo {
//传递对象的集合
private static Map<Thread, Integer> map1 = new HashMap<>();
private static Map<Thread, Integer> map2 = new HashMap<>();
public static void main(String[] args){
MyThread myThread1 = new MyThread(map1);
MyThread myThread2 = new MyThread(map2);
myThread1.start();
myThread2.start();
System.out.println("主线程"+Thread.currentThread().getName()+"执行完毕");
}
}
ThreadLocal:
public class Personal implements Cloneable{
private String name;
private int age;
private byte sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public byte getSex() {
return sex;
}
public void setSex(byte sex) {
this.sex = sex;
}
@Override
protected Object clone(){
Personal personal = null;
try {
personal = (Personal) super.clone();
personal.name = this.name;
personal.age = this.age;
personal.sex = this.sex;
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return personal;
}
}
public class MyThread2 extends Thread {
private ThreadLocal<Personal> threadLocal;
private int flag;
public MyThread2(int flag, ThreadLocal<Personal> threadLocal){
this.threadLocal = threadLocal;
this.flag = flag;
}
@Override
public void run() {
synchronized (this){
Personal personal = new Personal();
personal.setAge(11);
personal.setName("zhangsan");
personal.setSex((byte) 1);
threadLocal.set(personal);
if(flag == 1){
Personal otherpersonal = (Personal) personal.clone();
otherpersonal.setName("lisi");
threadLocal.set(otherpersonal);
}
System.out.println("2:"+threadLocal.get().getName()+"----"+threadLocal.get().getAge()+"-----"+threadLocal.get().getSex());
}
}
}
public class ThreadLocalDemo {
//传递对象的集合
private static ThreadLocal<Personal> threadLocal1 = new ThreadLocal<>();
private static ThreadLocal<Personal> threadLocal2 = new ThreadLocal<>();
public static void main(String[] args){
MyThread2 myThread1 = new MyThread2(1, threadLocal1);
MyThread2 myThread2 = new MyThread2(2, threadLocal2);
myThread1.start();
myThread2.start();
System.out.println("主线程"+Thread.currentThread().getName()+"执行完毕");
}
}
两者之间貌似并没有什么区别?应该是我对这两者之间的区别还没搞清楚,之后会补充。(这里我用了浅克隆,大家补脑的话可以看一下原型设计模式)
源码分析:
源码不多,只有700多行,这里因为篇幅的问题就不全部贴出来了
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
private T setInitialValue() {
T value = initialValue();
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
return value;
}
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
public void remove() {
ThreadLocalMap m = getMap(Thread.currentThread());
if (m != null)
m.remove(this);
}
void createMap(Thread t, T firstValue) {
t.threadLocals = new ThreadLocalMap(this, firstValue);
}
这里只贴出那么多了, 是不是有种似曾相识的感觉,像Map集合。
总结:
个人感觉ThreadLocal理解起来还是比较容易的,但是由于读了很多相关的文献,造成了思维的混乱,但是个人理解的结果还是和文章开头所说的内容是差不多的。就目前,我把ThreadLocal当成了一个工具,一个操作容器ThreadLocalMap的工具,可以传递复杂数据。
最后,欢迎大佬来指出文章的错误,谢谢了!