java多线程学习(三) 之 ThreadLocal
ThreadLocal 中文可以叫 线程变量 官方解释 This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable. 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). 这个类提供一个线程局部变量,意思就是变量只在该线程内可见,对于每个线程都可以用get和set方法获取属于这个线程自己的变量。ThreadLocal变量通常定义在那些想和线程绑定的类里面,例如访问者的ID,事务ID等等。 官方举例: import java.util.concurrent.atomic.AtomicInteger; public class ThreadId { private static final AtomicInteger nextId = new AtomicInteger(0); private static final ThreadLocal threadId = new ThreadLocal() { @Override protected Integer initialValue() { return nextId.getAndIncrement(); } }; // Returns the current thread's unique ID, // assigning it if necessary public static int get() { return threadId.get(); } } 其中threadId就是一个线程变量。具体的使用可以是这样的: ...