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 + "]";
        }
        
        
        
        
    
    }

    输出:

  • 相关阅读:
    hdoj2159【二位费用背包】
    POJ2367【拓扑排序】
    POJ2371【水题】
    POJ2369【循环节】
    POJ2370【水题】
    POJ2365【几何】
    POJ2366【二分】
    POJ1276【多重背包】
    瞎说一波3种基本背包问题【希望巨巨们指出错误】
    Codeforces 550B 【暴力】
  • 原文地址:https://www.cnblogs.com/pecool/p/13855458.html
Copyright © 2011-2022 走看看