ThreadLocal

简介:

ThreadLocal并不是一个Thread,而是Thread的局部变量,也许把它命名为ThreadLocalVariable更容易让人理解一些。

当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。

从线程的角度看,目标变量就象是线程的本地变量,这也是类名中“Local”所要表达的意思。

ThreadLocal的接口方法                                                              

ThreadLocal类接口很简单,只有4个方法,我们先来了解一下:

  • void set(Object value)

 

设置当前线程的线程局部变量的值。

  • public Object get()

 

该方法返回当前线程所对应的线程局部变量。

  • public void remove()

 

将当前线程局部变量的值删除,目的是为了减少内存的占用,该方法是JDK 5.0新增的方法。需要指出的是,当线程结束后,对应该线程的局部变量将自动被垃圾回收,所以显式调用该方法清除线程的局部变量并不是必须的操作,但它可以加快内存回收的速度。

  • protected Object initialValue()

 

返回该线程局部变量的初始值,该方法是一个protected的方法,显然是为了让子类覆盖而设计的。这个方法是一个延迟调用方法,在线程第1次调用get()或set(Object)时才执行,并且仅执行1次。ThreadLocal中的缺省实现直接返回一个null。

值得一提的是,在JDK5.0中,ThreadLocal已经支持泛型,该类的类名已经变为ThreadLocal <T>。API方法也相应进行了调整,新版本的API方法分别是void set(T value)、T get()以及T initialValue()。

ThreadLocal维护变量                                                                

ThreadLocal是如何做到为每一个线程维护变量的副本的呢?其实实现的思路很简单:在ThreadLocal类中有一个Map,用于存储每一个线程的变量副本,Map中元素的键为线程对象,而值对应线程的变量副本。我们自己就可以提供一个简单的实现版本:

复制代码
public class SimpleThreadLocal {
    private Map valueMap = Collections.synchronizedMap(new HashMap());
    public void set(Object newValue) {
        valueMap.put(Thread.currentThread(), newValue);//①键为线程对象,值为本线程的变量副本
    }
    public Object get() {
        Thread currentThread = Thread.currentThread();
        Object o = valueMap.get(currentThread);//②返回本线程对应的变量
        if (o == null && !valueMap.containsKey(currentThread)) {
        //③如果在Map中不存在,放到Map中保存起来。
            o = initialValue();
            valueMap.put(currentThread, o);
        }
        return o;
    }
    public void remove() {
        valueMap.remove(Thread.currentThread());
    }
    public Object initialValue() {
        return null;
    }
}
复制代码

虽然上面代码ThreadLocal实现版本显得比较幼稚,但它和JDK所提供的ThreadLocal类在实现思路上是相近的。

一个TheadLocal实例                                                                  

下面,我们通过一个具体的实例了解一下ThreadLocal的具体使用方法。

复制代码
public class SequenceNumber {
    //①通过匿名内部类覆盖ThreadLocal的initialValue()方法,指定初始值
    private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>(){
        public Integer initialValue(){
        return 0;
        }
    };
    //②获取下一个序列值
    public int getNextNum(){
        seqNum.set(seqNum.get()+1);
        return seqNum.get();
    }
    public static void main(String[] args)
    {
        SequenceNumber sn = new SequenceNumber();
        //③ 3个线程共享sn,各自产生序列号
        TestClient t1 = new TestClient(sn);
        TestClient t2 = new TestClient(sn);
        TestClient t3 = new TestClient(sn);
        t1.start();
        t2.start();
        t3.start();
    }
    private static class TestClient extends Thread
    {
        private SequenceNumber sn;
        public TestClient(SequenceNumber sn) {
            this.sn = sn;
        }
        public void run()
        {
            for (int i = 0; i < 3; i++) {//④每个线程打出3个序列值
            System.out.println("thread["+Thread.currentThread().getName()+
            "] sn["+sn.getNextNum()+"]");
        }
    }
}
复制代码

通常我们通过匿名内部类的方式定义ThreadLocal的子类,提供初始的变量值,如例子中①处所示。TestClient线程产生一组序列号,在③处,我们生成3个TestClient,它们共享同一个SequenceNumber实例。运行以上代码,在控制台上输出以下的结果:

复制代码
thread[Thread-2] sn[1]
thread[Thread-0] sn[1]
thread[Thread-1] sn[1]
thread[Thread-2] sn[2]
thread[Thread-0] sn[2]
thread[Thread-1] sn[2]
thread[Thread-2] sn[3]
thread[Thread-0] sn[3]
thread[Thread-1] sn[3]
复制代码

考察输出的结果信息,我们发现每个线程所产生的序号虽然都共享同一个SequenceNumber实例,但它们并没有发生相互干扰的情况,而是各自产生独立的序列号,这是因为我们通过ThreadLocal为每一个线程提供了单独的副本。

ThreadLocal的作用                                                                   

ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访问的,也访问不到的。各个线程中访问的是不同的对象。(注意这里说的只是“一般情况”,如果通过ThreadLocal.set() 到线程中的对象是多线程共享的同一个对象,各个线程中访问的将是同一个共享对象)。

1.提供了保存对象的方法:每个线程中都有一个自己的ThreadLocalMap类对象,可以将线程自己的对象保持到其中,各管各的,线程可以正确的访问到自己的对象。

2.避免参数传递的方便的对象访问方式:将一个共用的ThreadLocal静态实例作为key,将不同对象的引用保存到不同线程的ThreadLocalMap中,然后在线程执行的各处通过这个静态ThreadLocal实例的get()方法取得自己线程保存的那个对象,避免了将这个对象作为参数传递的麻烦。

理解ThreadLocal中提到的变量副本                                                 

“当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本” —— 并不是通过ThreadLocal.set( )实现的,而是每个线程使用“new对象”(或拷贝) 的操作来创建对象副本, 通过ThreadLocal.set()将这个新创建的对象的引用保存到各线程的自己的一个map中,每个线程都有这样一个map,执行ThreadLocal.get()时,各线程从自己的map中取出放进去的对象,因此取出来的是各自自己线程中的对象(ThreadLocal实例是作为map的key来使用的)。

如果ThreadLocal.set( )进去的对象是多线程共享的同一个对象,那么ThreadLocal.get( )取得的还是这个共享对象本身 —— 那么ThreadLocal还是有并发访问问题的!

复制代码
/* 
 * 如果ThreadLocal.set()进去的是一个多线程共享对象,那么Thread.get()获取的还是这个共享对象本身—————并不是该共享对象的副本。 
 * 假如:其中其中一个线程对这个共享对象内容作了修改,那么将会反映到其它线程获取的共享对象中————所以说 ThreadLocal还是有并发访问问题的! 
 */  
public class Test implements Runnable  
{  
    private ThreadLocal<Person> threadLocal = new ThreadLocal<Person>();  
      
    private Person person;  
      
    public Test(Person person)  
    {  
        this.person = person;  
    }  
      
    public static void main(String[] args) throws InterruptedException  
    {  
        //多线程共享的对象  
        Person sharePerson = new Person(110,"Sone");  
        Test test = new Test(sharePerson);  
          
        System.out.println("sharePerson原始内容:"+sharePerson);  
          
        Thread th = new Thread(test);  
        th.start();  
        th.join();  
          
        //通过ThreadLocal获取对象  
        Person localPerson = test.getPerson();  
          
        System.out.println("判断localPerson与sharePerson的引用是否一致:"+(localPerson==localPerson));  
        System.out.println("sharePerson被改动之后的内容:"+sharePerson);  
    }  
      
    @Override  
    public void run()  
    {  
        String threadName = Thread.currentThread().getName();  
        System.out.println(threadName+":Get a copy of the variable and change!!!");  
        Person p = getPerson();  
        p.setId(741741);  
        p.setName("Boy");  
    }  
      
    public Person getPerson(){  
        Person p = (Person)threadLocal.get();  
        if (p==null)  
        {  
            p= this.person;  
            //set():进去的是多线程共享的对象  
            threadLocal.set(p);  
        }  
        return p;  
    }
复制代码

ThreadLocal使用的一般步骤                                                         

1、在多线程的类(如ThreadDemo类)中,创建一个ThreadLocal对象threadXxx,用来保存线程间需要隔离处理的对象xxx。

2、在ThreadDemo类中,创建一个获取要隔离访问的数据的方法getXxx(),在方法中判断,若ThreadLocal对象为null时候,应该new()一个隔离访问类型的对象,并强制转换为要应用的类型。

3、在ThreadDemo类的run()方法中,通过getXxx()方法获取要操作的数据,这样可以保证每个线程对应一个数据对象,在任何时刻都操作的是这个对象。

Code                                                                                   

复制代码
/**
 * 学生
 */
public class Student {
    private int age = 0;   //年龄
 
    public int getAge() {
        return this.age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
}
复制代码
复制代码
/**
 * 多线程下测试程序
 */
public class ThreadLocalDemo implements Runnable {
    //创建线程局部变量studentLocal,在后面你会发现用来保存Student对象
    private final static ThreadLocal studentLocal = new ThreadLocal();
 
    public static void main(String[] agrs) {
        ThreadLocalDemo td = new ThreadLocalDemo();
        Thread t1 = new Thread(td, "a");
        Thread t2 = new Thread(td, "b");
        t1.start();
        t2.start();
    }
 
    public void run() {
        accessStudent();
    }
 
    /**
     * 示例业务方法,用来测试
     */
    public void accessStudent() {
        //获取当前线程的名字
        String currentThreadName = Thread.currentThread().getName();
        System.out.println(currentThreadName + " is running!");
        //产生一个随机数并打印
        Random random = new Random();
        int age = random.nextInt(100);
        System.out.println("thread " + currentThreadName + " set age to:" + age);
        //获取一个Student对象,并将随机数年龄插入到对象属性中
        Student student = getStudent();
        student.setAge(age);
        System.out.println("thread " + currentThreadName + " first read age is:" + student.getAge());
        try {
            Thread.sleep(500);
        }
        catch (InterruptedException ex) {
            ex.printStackTrace();
        }
        System.out.println("thread " + currentThreadName + " second read age is:" + student.getAge());
    }
 
    protected Student getStudent() {
        //获取本地线程变量并强制转换为Student类型
        Student student = (Student) studentLocal.get();
        //线程首次执行此方法的时候,studentLocal.get()肯定为null
        if (student == null) {
            //创建一个Student对象,并保存到本地线程变量studentLocal中
            student = new Student();
            studentLocal.set(student);
        }
        return student;
    }
}
复制代码

运行结果:

复制代码
a is running! 
thread a set age to:76 
b is running! 
thread b set age to:27 
thread a first read age is:76 
thread b first read age is:27 
thread a second read age is:76 
thread b second read age is:27
复制代码

可以看到a、b两个线程age在不同时刻打印的值是完全相同的。这个程序通过妙用ThreadLocal,既实现多线程并发,游兼顾数据的安全性。

Code                                                                                  

下面通过这样一个例子来说明:模拟一个游戏,预先随机设定一个[1, 10]的整数,然后每个玩家去猜这个数字,每个玩家不知道其他玩家的猜测结果,看谁用最少的次数猜中这个数字。

这个游戏确实比较无聊,不过这里恰好可以把每个玩家作为一个线程,然后用ThreadLocal来记录玩家猜测的历史记录,这样就很容易理解ThreadLocal的作用。

Judge:用来设定目标数字以及判断猜测的结果。

Player:每个Player作为一个线程,多个Player并行地去尝试猜测,猜中时线程终止。

Attempt:具有ThreadLocal字段和猜测动作静态方法的类,ThreadLocal用于保存猜过的数字。

Record:保存历史记录的数据结构,有一个List<Integer>字段。

ThreadLocal为了可以兼容各种类型的数据,实际的内容是再通过set和get操作的对象,详见Attempt的getRecord()。

运行的时候,每个Player Thread都是去调用Attemp.guess()方法,进而操作同一个ThreadLocal变量history,但却可以保存每个线程自己的数据,这就是ThreadLocal的作用。

复制代码
public class ThreadLocalTest {
    
    public static void main(String[] args) {
        Judge.prepare();
        new Player(1).start();
        new Player(2).start();
        new Player(3).start();
    }
    
}

class Judge {
    
    public static int MAX_VALUE = 10;
    private static int targetValue;
    
    public static void prepare() {
        Random random = new Random();
        targetValue = random.nextInt(MAX_VALUE) + 1;
    }
    
    public static boolean judge(int value) {
        return value == targetValue;
    }
    
}

class Player extends Thread {
    
    private int playerId;
    
    public Player(int playerId) {
        this.playerId = playerId;
    }
    
    @Override
    public void run() {
        boolean success = false;
        while(!success) {
            int value = Attempt.guess(Judge.MAX_VALUE);
            success = Judge.judge(value);
            System.out.println(String.format("Plyaer %s Attempts %s and %s", playerId, value, success ? " Success" : "Failed"));
        }
        Attempt.review(String.format("[IFNO] Plyaer %s Completed by ", playerId));
    }
    
}

class Attempt {
    
    private static ThreadLocal<Record> history = new ThreadLocal<Record>();
    
    public static int guess(int maxValue) {
        Record record = getRecord();
        Random random = new Random();
        int value = 0;
        do {
            value = random.nextInt(maxValue) + 1;
        } while (record.contains(value));
        record.save(value);
        return value;
    }
    
    public static void review(String info) {
        System.out.println(info + getRecord());
    }
    
    private static Record getRecord() {
        Record record = history.get();
        if(record == null) {
            record = new Record();
            history.set(record);
        }
        return record;
    }
    
}

class Record {
    
    private List<Integer> attemptList = new ArrayList<Integer>();;
    
    public void save(int value) {
        attemptList.add(value);
    }
    
    public boolean contains(int value) {
        return attemptList.contains(value);
    }
    
    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append(attemptList.size() + " Times: ");
        int count = 1;
        for(Integer attempt : attemptList) {
            buffer.append(attempt);
            if(count < attemptList.size()) {
                buffer.append(", ");
                count++;
            }
        }
        return buffer.toString();
    }
    
}
复制代码

运行结果

复制代码
Plyaer 2 Attempts 8 and Failed
Plyaer 3 Attempts 6 and Failed
Plyaer 1 Attempts 5 and Failed
Plyaer 2 Attempts 7 and  Success
Plyaer 3 Attempts 9 and Failed
Plyaer 1 Attempts 9 and Failed
Plyaer 3 Attempts 2 and Failed
Plyaer 1 Attempts 2 and Failed
[IFNO] Plyaer 2 Completed by 2 Times: 8, 7
Plyaer 3 Attempts 4 and Failed
Plyaer 1 Attempts 1 and Failed
Plyaer 3 Attempts 5 and Failed
Plyaer 1 Attempts 3 and Failed
Plyaer 3 Attempts 1 and Failed
Plyaer 1 Attempts 10 and Failed
Plyaer 3 Attempts 8 and Failed
Plyaer 1 Attempts 6 and Failed
Plyaer 3 Attempts 7 and  Success
Plyaer 1 Attempts 4 and Failed
[IFNO] Plyaer 3 Completed by 8 Times: 6, 9, 2, 4, 5, 1, 8, 7
Plyaer 1 Attempts 7 and  Success
[IFNO] Plyaer 1 Completed by 9 Times: 5, 9, 2, 1, 3, 10, 6, 4, 7
复制代码

hreadLocal  get()                                                                    

关于ThreadLocal的原理,可以从其get()方法的实现来看

复制代码
public class ThreadLocal<T> {
    ...
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null)
                return (T)e.value;
        }
        return setInitialValue();
    }


    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }
    ...
}
复制代码

执行get()时首先获取当前的Thread,再获取Thread中的ThreadLocalMap - t.threadLocals,并以自身为key取出实际的value。于是可以看出,ThreadLocal的变量实际还是保存在Thread中的,容器是一个Map,Thread用到多少ThreadLocal变量,就会有多少以其为key的Entry。

我是天王盖地虎的分割线       




本文转自我爱物联网博客园博客,原文链接:http://www.cnblogs.com/yydcdut/p/3959430.html,如需转载请自行联系原作者

相关文章
|
6月前
|
存储 安全 Java
【ThreadLocal】
【ThreadLocal】
|
3月前
|
存储 Java
ThreadLocal 有什么用
ThreadLocal 有什么用
21 0
|
4月前
|
存储
ThreadLocal
ThreadLocal
26 0
|
7月前
|
Java
ThreadLocal详解
ThreadLocal详解
39 0
|
10月前
|
存储 SQL Java
ThreadLocal的其他应用
request对象跟PageHelper
84 0
|
11月前
|
存储 Java 数据库连接
对ThreadLocal的一点了解
ThreadLocal是线程变量,它为每个线程提供单独的存储空间。其主要作用是做线程间的数据隔离,也可以用于在同一个线程间方便地进行数据共享。(对于多线程资源共享,加锁机制采用“时间换空间”,ThreadLocal采用“空间换时间”)
102 0
|
存储 Java
ThreadLocal相关使用
ThreadLocal相关使用
162 0
ThreadLocal相关使用
|
存储 安全 Java
我把 ThreadLocal 能问的,都写了(上)
我把 ThreadLocal 能问的,都写了(上)
我把 ThreadLocal 能问的,都写了(上)