美文网首页
ThreadLocal源码解析

ThreadLocal源码解析

作者: 芸芸水中一滴水 | 来源:发表于2017-07-10 20:06 被阅读0次

    概述

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

    构造方法

    1. ThreadLocal()

    成员变量

    1. 222

    成员方法

    1. initialValue()
        protected T initialValue() {
            return null;
        }
    

    返回变量的初始值,默认返回为空,可在子类中复写该方法;

    1. get()
        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;
        }
    

    返回当前线程对应的本地变量副本值;

    1. set(T 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);
        }
    
        // 为线程创建本地变量集合
        void createMap(Thread t, T firstValue) {
            t.threadLocals = new ThreadLocalMap(this, firstValue);
        }
    

    设置当前线程对应的本地变量副本值;

    1. remove()
        public void remove() {
             ThreadLocalMap m = getMap(Thread.currentThread());
             if (m != null)
                 m.remove(this);
         }
    

    移除当前线程对应的本地变量副本;

    实例

    public class Main {
        
        private ThreadLocal<Integer> mThreadLocal = new ThreadLocal<Integer>() {
            
            @Override
            protected Integer initialValue() {
                return 0;
            }
        };
        
        private int getNext() {
            mThreadLocal.set(mThreadLocal.get() + 1);
            return mThreadLocal.get();
        }
    
        public static void main(String[] args) {
            Main main = new Main();
            Task task1 = new Task(main);
            Task task2 = new Task(main);
            Task task3 = new Task(main);
            Task task4 = new Task(main);
            task1.start();
            task2.start();
            task3.start();
            task4.start();
        }
        
        static class Task extends Thread {
            private Main main;
            
            private Task(Main main) {
                this.main = main;
            }
            
            @Override
            public void run() {
                for (int i = 0; i < 3; i++) {
                    System.out.println(Thread.currentThread().getName() + " -----> " + main.getNext());
                }
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:ThreadLocal源码解析

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