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

    测试demo

    public class MainTest{
        
        private static final ThreadLocal < Person > local = 
                new ThreadLocal < Person > () {
                    @Override protected Person initialValue() {
                        return Person.getPerson();
                }
            };
        
        public static void main(String[] args) throws InterruptedException {
            for(int i = 0; i < 10;i++) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Person person = Person.getPerson();
                        int age = (int)(Math.random()*100);
                        person.setAge(age);
                        person.setName(""+age);
                        local.set(person);
                        System.out.println(local.get());
                        
                    }
                }).start();;
                Thread.sleep(1000);
            }
        }
        
    }
    public class Person {
    
        private String name;
        
        private Integer age;
        
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        private static Person person = null;
        
        private Person() {}
        
        public synchronized static Person getPerson() {
            if(person == null) {
                person = new Person();
            }
            return person;
        }
        
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "Person [name=" + name + ", age=" + age + "]";
        }
        
        
        
        
    
    }

    输出:

  • 相关阅读:
    c# ThreadPool 判断子线程全部执行完毕的四种方法
    很多人都爱玩的lol..
    Go 的位操作
    wrk压测工具
    Go函数作为值与类型
    家用PC发展设想
    开车的烦恼
    一款一体机的设想
    nodejs开发环境的搭建
    Python网页抓取程序(续)
  • 原文地址:https://www.cnblogs.com/pecool/p/13855458.html
Copyright © 2011-2022 走看看