ThreadLocal类的用法
在ThreadLocal类中有一个Map,用于存储每一个线程的变量的副本,同步机制采用了“以时间换空间”的方式,而ThreadLocal采用了“以空间换时间”的方式
案例:
package demo; import java.util.Random; public class ThreadLocalShareData2 { static ThreadLocal<People> threadLocal = new ThreadLocal<People>(); public static void main(String[] args) { for (int i = 0; i < 2; i++) { new Thread(new Runnable() { @Override public void run() { int data = new Random().nextInt(); People people = new People().getInstance(); people.setName("name"+data); people.setAge(data); // System.out.println(Thread.currentThread().getName()+" set name "+people.getName()+" set age "+people.getAge()); new A().get(); new B().get(); } }).start(); } } static class A{ public void get(){ System.out.println("A: "+Thread.currentThread().getName() +"get name "+new People().getInstance().getName()+" get age "+new People().getInstance().getAge()); } } static class B{ public void get(){ System.out.println("B: "+Thread.currentThread().getName() +"get name "+new People().getInstance().getName()+" get age "+new People().getInstance().getAge()); } } static class People{ private People(){ } public People getInstance(){ People people = threadLocal.get(); if(people == null){ people = new People(); threadLocal.set(people); } return people; } private int age; private String name; public int getAge() { return age; } public String getName() { return name; } public void setAge(int age) { this.age = age; } public void setName(String name) { this.name = name; } } }
执行结果: