ThreadLocal 的作用和目的:用于实现线程内的数据共享,即对于相同的程序代码,多个模块在同一个线程中运行时要共享一份数据,而在另外线程中运行时又共享另外一份数据。
protected synchronized Object initialValue() { return new Integer(nextNum++); } } //获取ThreadLocal中的独享对象 public static int get() { return ((Integer) (threadLocalNum.get())).intValue(); }}
每个线程调用全局 ThreadLocal 对象的 set 方法,在 set 方法中,首先根据当前线程获取当前线程的ThreadLocalMap 对象,然后往这个 map 中插入一条记录, key 其实是 ThreadLocal 对象, value 是各自的 set方法传进去的值。也就是每个线程其实都有一份自己独享的 ThreadLocalMap 对象,该对象的 Key 是 ThreadLocal对象,值是用户设置的具体值。
ThreadLocal的使用示例:
//第一个示例:public class ThreadLocalNum{
private static int nextNum = 0; private static ThreadLocal threadLocalNum= new ThreadLocal() {
protected synchronized Object initialValue() { return new Integer(nextNum++); } } //获取ThreadLocal中的独享对象 public static int get() { return ((Integer) (threadLocalNum.get())).intValue(); }}
//第二个示例:
public class ThreadLocalDemo implements Runnable{
ThreadLocal<Student> threadLocal = new ThreadLocal<Student>();//独享student的ThreadLocal
public void run() {
String currentThreadName = Thread.currentThread().getName();
System.out.println(currentThreadName + "is running--------------------");
Random random = new Random();
int a = random.nextInt(100);
System.out.println(currentThreadName + "is set age :" + a);
Student stu = getStu();
stu.setAge(a);
System.out.println(currentThreadName + "is first get age :" + stu.getAge());
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(currentThreadName + "id second get age :" + stu.getAge());
}
public static void main(String[] args) {
ThreadLocalDemo demo = new ThreadLocalDemo();
Thread t1 = new Thread(demo,"t1111111");
Thread t2 = new Thread(demo,"t222222222");
t1.start();
t2.start();
}
private Student getStu() {
Student stu = threadLocal.get();
if (stu == null) {
stu = new Student();
threadLocal.set(stu);
}
return stu;
}
}
class Student{
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}