ThreadLocal原理:
1、查看ThreadLocal的set方法可以看到getMap方法通过当前线程获取当前线程的ThreadLocalMap
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
2、在Thread中有
public class Thread{
ThreadLocal.ThreadLocalMap threadLocals = null;
}
ThreadLocal.ThreadLocalMap是Thread中的变量,也就是说每个Thread有唯一的ThreadLocalMap(在初次set数据的时候创建),而ThreadLocalMap的key为当前操作的ThreadLocal,value为设置的value
以下代码是ThreadLocal保证3个线程各自生成数据
package com.gcl.threadlocal;
class Res
{
private int count;
private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>()
{
protected Integer initialValue() {
return 0;
};
};
public int getNum()
{
count = threadLocal.get() + 1;
threadLocal.set(count);
return count;
}
}
class ThreadLocalThread implements Runnable
{
private Res res;
public ThreadLocalThread(Res res)
{
this.res = res;
}
@Override
public void run()
{
for(int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName() + ":" + res.getNum());
}
}
}
public class ThreadLocalDemo
{
public static void main(String[] args)
{
Res res = new Res();
ThreadLocalThread localThread = new ThreadLocalThread(res);
Thread thread1 = new Thread(localThread,"thread1");
Thread thread2 = new Thread(localThread,"thread2");
Thread thread3 = new Thread(localThread,"thread3");
thread1.start();
thread2.start();
thread3.start();
}
}