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

}

输出: