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的工具类,两个线程获取的值互相不干扰.

  • 相关阅读:
    iOS 国际化
    iOS iOS7 20px 处理
    iOS 导航栏
    android Tab =viewpager+fragmnet
    Android fragment 想activity 传送数据
    sass sublime text 2 gulp ionic
    HTML5 Notification消息通知
    浅谈设备分辨比
    offsetwidth/clientwidth的区别
    移动端网页布局中需要注意事项以及解决方法总结
  • 原文地址:https://www.cnblogs.com/qinggege/p/5217154.html
Copyright © 2011-2022 走看看