ThreadLocal

作者: kanaSki | 来源:发表于2019-07-02 22:35 被阅读0次

    线程本地存储区域。ThreadLocal能够放一个线程级别的变量,其本身能够被多个线程共享使用,并且能够达到线程安全的目的。JDK中建议ThreadLocal定义为private static。
    内部存储结构类似map,key是存储信息,value是存储内容。
    常用set\get\initialValue方法。

    /**
     * ThreadLocal表示每个线程自身的存储区域:本地、局部区域
     */
    public class ThreadLocalTest01 {
        //    private static ThreadLocal<Integer> threadLocal = new ThreadLocal();
        //    更改初始值
    //    private static ThreadLocal<Integer> threadLocal = new ThreadLocal() {
    //        @Override
    //        protected Object initialValue() {
    //            return 200;
    //        }
    //    };
        private static ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 200);
    
        public static void main(String[] args) {
            // 设置值
            threadLocal.set(99);
            System.out.println(Thread.currentThread().getName() + "-->" + threadLocal.get());   // 200
            new Thread(new ThreadLocalTest01.MyRun()).start();
        }
    
    
        public static class MyRun implements Runnable {
    
            @Override
            public void run() {
                threadLocal.set(11);
                System.out.println(Thread.currentThread().getName() + "-->" + threadLocal.get());   // 11
            }
        }
    }
    
    
    

    每个线程存储自身的数据,更改不会影响其他的线程。

    /**
     * ThreadLocal表示每个线程自身的存储区域:本地、局部区域
     */
    public class ThreadLocalTest01 {
        private static ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 1);
    
        public static void main(String[] args) {
            for (int i = 0; i < 5; i++) {
                new Thread(new ThreadLocalTest01.MyRun()).start();
            }
        }
    
    
        public static class MyRun implements Runnable {
    
            @Override
            public void run() {
                Integer integer = threadLocal.get();
                System.out.println(Thread.currentThread().getName() + "-->" + integer);   // 1
                threadLocal.set(integer - 1);
                System.out.println(Thread.currentThread().getName() + "-->" + threadLocal.get());   // 0
            }
        }
    }
    
    
    

    InheritableThreadLocal 继承上下文环境的数据,可以将数据进行共享。

    public class ThreadLocalTest01 {
        private static ThreadLocal<Integer> threadLocal = new InheritableThreadLocal<>();
    
        public static void main(String[] args) {
            threadLocal.set(2);
            System.out.println(Thread.currentThread().getName() + "-->" + threadLocal.get());
            // 线程由main线程开辟,将数据拷贝一份给子线程
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "-->" + threadLocal.get());   // 2
            }).start();
        }
    }
    
    

    相关文章

      网友评论

        本文标题:ThreadLocal

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