What is a ThreadLocal class?
ThreadLocal is a handy class for simplifying development of thread-safe concurrent programs by making the object stored in this class not sharable between threads. ThreadLocal class encapsulates non-thread-safe classes to be safely used in a multi-threaded environment and also allows you to create per-thread-singleton.
ThreadLocal也是为了解决多线程中的对共享变量的访问冲突。
在普通的同步机制中,是通过对象加锁来实现多个线程对共享变量的安全访问的。
在1.5以前的版本中,synchronized是自动释放锁。
在JDK1.5的版本中,提供了类java.util.concurrent.locks.Lock,它比synchronized更精确和有更高的性能,使用时需要知道什么时候对变量进行读写,什么时候锁定这个对象,什么时候又需要释放该对象的锁等。
而ThreadLocal就从另一个角度来解决多线程的并发访问,ThreadLocal会为每一个线程维护一个和该线程绑定的变量的副本。
如果需要进行多个线程之间进行通信,则使用同步机制;如果需要隔离多个线程之间的共享冲突,可以使用ThreadLocal。