美文网首页
多线程(6) — ThreadLocal线程范围内的共享数据

多线程(6) — ThreadLocal线程范围内的共享数据

作者: 烧杰 | 来源:发表于2018-04-17 22:22 被阅读0次

    看问题:

    package ThreadPractice;
    
    import java.util.Random;
    
    /**
     * Created by qiaorenjie on 2018/3/25.
     */
    public class ThreadScopeShareData {
    
        private static int data = 0;
        public static void main(String[] args) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    data = new Random().nextInt();
                    System.out.println(Thread.currentThread().getName()
                                    + " 放入数据:" + data);
                    new A().get();
                    new B().get();
                }
            }).start();
        }
    
        static class A{
            public void get(){
                System.out.println("A的" + Thread.currentThread().getName()
                        + " 获取数据:" + data);
            }
        }
    
        static class B{
            public void get(){
                System.out.println("B的" + Thread.currentThread().getName()
                        + " 获取数据:" + data);
            }
        }
    
    }
    
    ======console=====
    Thread-0 放入数据:-172518424
    A的Thread-0 获取数据:-172518424
    B的Thread-0 获取数据:-172518424
    

    一个线程的data都是一样的看起来没问题,但是加上for循环开启两个线程的时候出现了下面的问题:


    image.png
    image.png

    可见第一个线程放入的数据和后面调用A、B取得的数据不一样。所以怎么样让各自线程独立呢?


    image.png
    image.png

    可见通过Map就实现了各自线程的独立。

    这其中主要是因为共享数据是同一个对其的操作是一致的

    也就是说在多线程中要考虑后面的线程或方法对于共享变量的更改以及线程安全,而这里用Map将各个线程与数据隔离开来,实现了线程范围内的共享数据。

    ThreadLocal类就是为了解决这个问题而设计

    ThreadLocal类部分源码:

    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();
        }
    
        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;
        }
      ......
    static class ThreadLocalMap {
          .....
       static class Entry extends WeakReference<ThreadLocal> {
                /** The value associated with this ThreadLocal. */
                Object value;
    
                Entry(ThreadLocal k, Object v) {
                    super(k);
                    value = v;
                }
            }
          ......
          private ThreadLocalMap(ThreadLocalMap parentMap) {
                Entry[] parentTable = parentMap.table;
                int len = parentTable.length;
                setThreshold(len);
                table = new Entry[len];
    
                for (int j = 0; j < len; j++) {
                    Entry e = parentTable[j];
                    if (e != null) {
                        ThreadLocal key = e.get();
                        if (key != null) {
                            Object value = key.childValue(e.value);
                            Entry c = new Entry(key, value);
                            int h = key.threadLocalHashCode & (len - 1);
                            while (table[h] != null)
                                h = nextIndex(h, len);
                            table[h] = c;
                            size++;
                        }
                    }
                }
            }
          ........
    }
    

    由源码可以看出来ThreadLocal类其实就是给每一个操作的Thread对映一个ThreadLocalMap,而Entry(ThreadLocal k, Object v)以ThreadLocal为key,存储的数据为Object,将每个线程分开。由此实现了每个线程对数据的隔离。

    一个ThreadLocal代表一个变量,如果有几个ThreadLocal,则需要创建多个ThreadLocal,若有多个变量需要线程共享,可以先定义一个对象封装这多个变量,然后在ThreadLocal中存储这一个对象。

    public class ThreadLocalTest {
    
        static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
        static ThreadLocal<MyThreadScopeData> myThreadScopeData = new ThreadLocal<>();
    
        public static void main(String[] args) {
            for (int i = 0; i <2 ; i++) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int data = new Random().nextInt();
                        System.out.println(Thread.currentThread().getName()
                                + " 放入数据:" + data);
                        threadLocal.set(data);  // 这里默认对当前线程的数据操作:Thread.currentThread()
                        MyThreadScopeData myData = new MyThreadScopeData();
                        myData.setName("name" + data);
                        myData.setAge(data);
                        myThreadScopeData.set(myData);
                        new A().get();
                        new B().get();
                    }
                }).start();
            }
        }
    
        static class A{
            public void get(){
                int data = threadLocal.get();  // 不用输线程号,就是当前线程
                System.out.println("A的" + Thread.currentThread().getName()
                        + " 获取数据:" + data);
                MyThreadScopeData myData = myThreadScopeData.get();
                System.out.println("A的" + Thread.currentThread().getName()
                        + " 获取myData数据:" + myData.getName() + "," +
                        myData.getAge());
            }
        }
    
        static class B{
            public void get(){
                int data = threadLocal.get();
                System.out.println("B的" + Thread.currentThread().getName()
                        + " 获取数据:" + data);
            }
        }
    
    }
    
    class MyThreadScopeData{
    
        private String name;
        private int age;
    
        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;
        }
    }
    ======console=======
    Thread-0 放入数据:1185524060
    A的Thread-0 获取数据:1185524060
    A的Thread-0 获取myData数据:name1185524060,1185524060
    B的Thread-0 获取数据:1185524060
    Thread-1 放入数据:1025645101
    A的Thread-1 获取数据:1025645101
    A的Thread-1 获取myData数据:name1025645101,1025645101
    B的Thread-1 获取数据:1025645101
    
    

    通过将数据存到ThreadLocal或者数据量多时创建对象将对象放入ThreadLocal即可实现数据的隔离。

    由此已经实现了其功能

    (ThreadLocal在这里知乎上也有很多讨论
    https://www.zhihu.com/question/23089780

    但是这种方法不够好,每次都要new实例,能不能每个线程就一个实例节约空间,对代码进行重构。
    (从这里开始又涉及到—《Java设计模式》这一块儿内容,对于代码的优化与重构在公司里也极其看重,这一块儿内容也十分重要,后面有空可能会开辟新空间来讲)

    public class ThreadLocalTest {
    
        static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
        static ThreadLocal<MyThreadScopeData> myThreadScopeData = new ThreadLocal<>();
    
        public static void main(String[] args) {
            for (int i = 0; i <2 ; i++) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int data = new Random().nextInt();
                        System.out.println(Thread.currentThread().getName()
                                + " 放入数据:" + data);
                        threadLocal.set(data);  // 这里默认对当前线程的数据操作:Thread.currentThread()
    //                    MyThreadScopeData myData = new MyThreadScopeData();
    //                    myData.setName("name" + data);
    //                    myData.setAge(data);
    //                    myThreadScopeData.set(myData);
                        MyThreadScopeData.getThreadInstance().setName("name"+ data);
                        MyThreadScopeData.getThreadInstance().setAge(data);
                        new A().get();
                        new B().get();
                    }
                }).start();
            }
        }
    
        static class A{
            public void get(){
                int data = threadLocal.get();  // 不用输线程号,就是当前线程
                System.out.println("A的" + Thread.currentThread().getName()
                        + " 获取数据:" + data);
    //          MyThreadScopeData myData = myThreadScopeData.get();
                MyThreadScopeData myData = MyThreadScopeData.getThreadInstance();
    
                System.out.println("A的" + Thread.currentThread().getName()
                        + " 获取myData数据:" + myData.getName() + "," +
                        myData.getAge());
            }
        }
    
        static class B{
            public void get(){
                int data = threadLocal.get();
                System.out.println("B的" + Thread.currentThread().getName()
                        + " 获取数据:" + data);
                MyThreadScopeData myData = MyThreadScopeData.getThreadInstance();
                System.out.println("B的" + Thread.currentThread().getName()
                        + " 获取myData数据:" + myData.getName() + "," +
                        myData.getAge());
            }
        }
    
    }
    
    class MyThreadScopeData{
    
        private MyThreadScopeData(){}
    
          //1. 饿汉式:只有一个类的实例对象,不管是否调用实例对象都已经创建好了
    //    public static MyThreadScopeData getInstance(){
    //        return instance;
    //    }
    //    private static MyThreadScopeData instance = new MyThreadScopeData();
    
        //2. 懒汉式:等到需要的时候才创建。由于可能在第一个线程new了个MyThreadScopeData()还没有赋值
        //       CPU就切换产生两个对象,所以要加Synchronized保证线程安全
    //    public static synchronized MyThreadScopeData getInstance(){
    //        if (instance == null){
    //            instance = new MyThreadScopeData();
    //        }
    //        return instance;
    //    }
    //    private static MyThreadScopeData instance = null;
    
        //3. 用ThreadLocal
        public static MyThreadScopeData getThreadInstance(){  // 不用加synchronized
            MyThreadScopeData instance = map.get();
            if (instance == null){
                instance = new MyThreadScopeData();
                map.set(instance);
            }
            return instance;
        }
        private static ThreadLocal<MyThreadScopeData> map = new ThreadLocal<>();
    
        private String name;
        private int age;
    
        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;
        }
    }
    

    每一个线程对应一个容器对象把该线程所有数据装在这个容器里面,其他线程过来则对应另外一个容器对象。

    相关文章

      网友评论

          本文标题:多线程(6) — ThreadLocal线程范围内的共享数据

          本文链接:https://www.haomeiwen.com/subject/ubfkcftx.html