zoukankan      html  css  js  c++  java
  • ThreadLocal的使用

     用途

    当前线程的存储信息,每个线程独享. 比如用户浏览访问的节点信息,保证访问节点与存储节点的一致.

    代码:

    下面用一个简单的案例来说明怎么使用ThreadLocal

    package fx;
    
    /**
     * 线程存储工具类
     * @author lxz
     *
     */
    public class UserThreadLocalUtil {
        
        private static ThreadLocal<Integer> t1 = new ThreadLocal<Integer>();//存储年龄
        private static ThreadLocal<String> t2 = new ThreadLocal<String>();//存储姓名
    
        public static ThreadLocal<Integer> getT1() {
            return t1;
        }
    
        public static void setT1(ThreadLocal<Integer> t1) {
            UserThreadLocalUtil.t1 = t1;
        }
    
        public static ThreadLocal<String> getT2() {
            return t2;
        }
    
        public static void setT2(ThreadLocal<String> t2) {
            UserThreadLocalUtil.t2 = t2;
        }
    
        public static void main(String[] args) {
            Runnable thread1 = new Runnable() {
    
                public void run() {
                    UserThreadLocalUtil.getT1().set(18);
                    UserThreadLocalUtil.getT2().set("小明");
                    while(true){
                        System.out.println(UserThreadLocalUtil.getT1().get());
                        System.out.println(UserThreadLocalUtil.getT2().get());
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            Runnable thread2 = new Runnable() {
    
                public void run() {
                    UserThreadLocalUtil.getT1().set(20);
                    UserThreadLocalUtil.getT2().set("小红");
                    while(true){
                        System.out.println(UserThreadLocalUtil.getT1().get());
                        System.out.println(UserThreadLocalUtil.getT2().get());
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            Thread tt1 = new Thread(thread1);
            Thread tt2 = new Thread(thread2);
            tt1.start();
            tt2.start();
        }
    }

    测试结果:

    18
    小明
    20
    小红
    18
    小明
    20
    小红
    18
    20
    小红
    小明

    通过结果发现,即使调用的是static的工具类,两个线程获取的值互相不干扰.

  • 相关阅读:
    洛咕 P4131 [WC2005]友好的生物
    P3354 [IOI2005]Riv 河流
    洛咕 P3645 [APIO2015]雅加达的摩天楼
    洛咕 P4528 [CTSC2008]图腾
    CSDN不登录阅读全文(最新更新
    #6472. 「ICPC World Finals 2017」难以置信的任务 Mission Improbable
    #6435. 「PKUSC2018」星际穿越
    #2009. 「SCOI2015」小凸玩密室
    #2007. 「SCOI2015」国旗计划
    PKUWC2018题解
  • 原文地址:https://www.cnblogs.com/qinggege/p/5217154.html
Copyright © 2011-2022 走看看