简介
ThreadLocal为每个线程创建一个新的副本,个线程间不会相互影响。
用空间换时间。而synchronized用时间换空间
public class ThreadLocalDemo {
final static ThreadLocal<Person> tl = new ThreadLocal<Person>();
public static void main(String[] args) {
new Thread(()->{
try {
Thread.sleep(2000);
System.out.println(tl.get());
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(()->{
try {
Thread.sleep(1000);
tl.set(new Person());
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
class Person{
public String name;
}