• ThreadLocal用法


    1、使用实例:

    public class MyThreadLocal {
        private static final ThreadLocal<Object> threadLocal = new ThreadLocal<Object>() {
            /**
             * ThreadLocal没有被当前线程赋值时或当前线程刚调用remove方法后调用get方法,返回此方法值
             */
            @Override
            protected Object initialValue() {
                System.out.println("调用get方法时,当前线程共享变量没有设置,调用initialValue获取默认值!");
                return null;
            }
        };
    
        public static void main(String[] args) {
            new Thread(new MyIntegerTask("IntegerTask1")).start();
            /*new Thread(new MyStringTask("StringTask1")).start();
            new Thread(new MyIntegerTask("IntegerTask2")).start();
            new Thread(new MyStringTask("StringTask2")).start();*/
        }
    
        public static class MyIntegerTask implements Runnable {
            private String name;
    
            MyIntegerTask(String name) {
                this.name = name;
            }
    
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    // ThreadLocal.get方法获取线程变量
                    if (null == MyThreadLocal.threadLocal.get()) {
                        // ThreadLocal.et方法设置线程变量
                        MyThreadLocal.threadLocal.set(0);
                        System.out.println("线程" + name + ": 0");
                    } else {
                        int num = (Integer) MyThreadLocal.threadLocal.get();
                        MyThreadLocal.threadLocal.set(num + 1);
                        System.out.println("线程" + name + ": " + MyThreadLocal.threadLocal.get());
                        if (i == 3) {
                            MyThreadLocal.threadLocal.remove();
                        }
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
    
        }
    
        public static class MyStringTask implements Runnable {
            private String name;
    
            MyStringTask(String name) {
                this.name = name;
            }
    
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    if (null == MyThreadLocal.threadLocal.get()) {
                        MyThreadLocal.threadLocal.set("a");
                        System.out.println("线程" + name + ": a");
                    } else {
                        String str = (String) MyThreadLocal.threadLocal.get();
                        MyThreadLocal.threadLocal.set(str + "a");
                        System.out.println("线程" + name + ": " + MyThreadLocal.threadLocal.get());
                    }
                    try {
                        Thread.sleep(800);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
    
        }
    }
    

      2、源码简要分析:

      

    测试:
    public class MyThreadLocal {                                                              
        private static final ThreadLocal<Object> threadLocal = new ThreadLocal<Object>();       
        public static void main(String[] args) {
         new Thread(new MyIntegerTask("IntegerTask1")).start();
      }
      public static class MyIntegerTask implements Runnable {
          @Override
            public void run() {
                if (null == MyThreadLocal.threadLocal.get()) {
                  MyThreadLocal.threadLocal.set(0);
                  System.out.println("线程本地值为: 0");
               }else {
                  int num = (Integer) MyThreadLocal.threadLocal.get();
                  MyThreadLocal.threadLocal.set(1);
                  System.out.println("线程本地值为: " + MyThreadLocal.threadLocal.get());
               }
              if (i == 1) {
                  MyThreadLocal.threadLocal.remove();
               }
            }
      }
    }
    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) {
                    @SuppressWarnings("unchecked")
                    T result = (T)e.value;
                    return result;
                }
            }
            return setInitialValue();
        }
        
        public void set(T value) {
            Thread t = Thread.currentThread();
            ThreadLocalMap map = getMap(t);
            if (map != null)
                map.set(this, value);
            else
                createMap(t, value);
        }
        
         public void remove() {
             ThreadLocalMap m = getMap(Thread.currentThread());
             if (m != null)
                 m.remove(this);
         }
         
        ThreadLocalMap getMap(Thread t) {
            return t.threadLocals;
        }
       
        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;
        }
        
        void createMap(Thread t, T firstValue) {
            t.threadLocals = new ThreadLocalMap(this, firstValue);
        }
             
        static class ThreadLocalMap {
            ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) {
                table = new Entry[INITIAL_CAPACITY];
                int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1);
                table[i] = new Entry(firstKey, firstValue);
                size = 1;
                setThreshold(INITIAL_CAPACITY);
            }    
        }
    }
    public  class Thread implements Runnable {
         ThreadLocal.ThreadLocalMap threadLocals = null;
    }
    

      

  • 相关阅读:
    bzoj 3027 [Ceoi2004]Sweet——生成函数
    bzoj 3028 食物——生成函数
    JZOJ 5461 购物 —— 贪心
    JZOJ 1003 [ 东莞市选 2007 ] 拦截导弹 —— 递推
    JZOJ 1667 ( bzoj 1801 ) [ AHOI 2009 ] 中国象棋 —— DP
    洛谷 P2055 [ ZJOI 2009 ] 假期的宿舍 —— 二分图匹配
    洛谷 P3398 仓鼠找sugar —— 树链剖分
    洛谷 P1083 [ NOIP 2012 ] 借教室 —— 线段树 / 二分差分数组
    bzoj 3895 取石子 —— 博弈论
    洛谷 P1312 [ NOIP 2011 ] Mayan游戏 —— 搜索+模拟
  • 原文地址:https://www.cnblogs.com/yaohuiqin/p/9930543.html
Copyright © 2020-2023  润新知