zoukankan      html  css  js  c++  java
  • jdk src 学习 Threadlocal

     示例:

    import java.io.Serializable;
    
    public class TestThreadLocal implements Serializable {
        /**
         * 
         */
        private static final long serialVersionUID = -1279921928557717157L;
    
        int age;
    
        public static void main(String[] argv) throws Exception {
    
            TestThreadLocal tt = new TestThreadLocal();
    
            Testthread t1 = new Testthread(tt);
            Testthread t2 = new Testthread(tt);
            Testthread t3 = new Testthread(tt);
    
            t1.start();
            t2.start();
            t3.start();
    
        }
    
         static int ii = 0;
    //    static Integer ii = 0;
    
        // public Integer getIi() {// 这个方式不行
        // ii ++;
        // return ii;
        // }
    
        public Integer getIi() {
            // tl.set( ii ++ ); // 这个方式也不行, 必须要下面的方式。
            tl.set(tl.get() + 1);
            return tl.get();
        }
    
        /**
         * { } 内部的初始化是必须的。  否则出现 nullpointexception 
         */
        ThreadLocal<Integer> tl = new ThreadLocal<Integer>() {
            protected Integer initialValue() {
                ii = 0;
                return ii;
            };
        };
    
    }
    
    class Testthread extends Thread {
    
        TestThreadLocal ttl;
    
        public Testthread(TestThreadLocal ttl) {
            this.ttl = ttl;
        }
    
        @Override
        public void run() {
            String name2 = Thread.currentThread().getName();
            for (int i = 0; i < 3; i++) {
                System.out.println(" name " + name2 + ttl.getIi());
            }
        }
    }
    
    ThreadLocal 的作用在于,将某些变量绑定到线程中去, 提供一种,线程安全的方式操作某些变量。

  • 相关阅读:
    layoutSubviews总结
    Vue.js:循环语句
    Vue.js:条件与循环
    Vue.js:模版语法
    Vue.js:起步
    Vue.js-Runoob:目标结构
    Vue.js-Runoob:安装
    Runoob-Vue.js:教程
    Vue.js:template
    培训-Alypay-Cloud:蚂蚁金融云知识点
  • 原文地址:https://www.cnblogs.com/FlyAway2013/p/5587936.html
Copyright © 2011-2022 走看看