今天要研究的是ThreadLocal,这个我在一年前学习JavaWeb基础的时候接触过一次,当时在baidu搜出来的第一篇博文ThreadLocal,在评论下很多开发者认为那博主理解错误,给出了很多有关的链接来指正(可原博主可能没上博客了,一直没做修改)。我也去学习了一番,可惜的是当时还没有记录的习惯,直到现在仅仅记住了一些当时学过的皮毛。
因此,做一些技术的记录是很重要的~同时,ThreadLocal也是面试非常常见的面试题,对Java开发者而言也是一个必要掌握的知识点~
当然了,如果我有写错的地方请大家多多包涵,欢迎在评论下留言指正~
一、什么是ThreadLocal声明:本文使用的是JDK 1.8
首先我们来看一下JDK的文档介绍:
/** * This class provides thread-local variables. These variables differ from * their normal counterparts in that each thread that accesses one (via its * {@code get} or {@code set} method) has its own, independently initialized * copy of the variable. {@code ThreadLocal} instances are typically private * static fields in classes that wish to associate state with a thread (e.g., * a user ID or Transaction ID). * * <p>For example, the class below generates unique identifiers local to each * thread. * A thread's id is assigned the first time it invokes {@code ThreadId.get()} * and remains unchanged on subsequent calls. */