java.lang.ThreadLocal<T>
类,对它的调用在不同线程中有不同的结果。
1.使用场景
有些类不是线程安全的,若想在多线程下使用,我们可以为每个线程绑定一个此类的对象。
2.常用方法
T java.lang.ThreadLocal. get()返回当前线程所持有的对象。
void java.lang.ThreadLocal. set(T value)
设置当前线程所持有的对象。
void java.lang.ThreadLocal. remove()
移除当前线程所持有的对象。
3.例子
可见:线程安全
4.原理浅析
第一段,个人发挥。
第二段,摘自jdk。
5.知名框架如何用
springmvc就在用。
package org.springframework.web.context.request;
/**
* Holder class to expose the web request in the form of a thread-bound
* {@link RequestAttributes} object
* ...
*/
public abstract class RequestContextHolder {
private static final ThreadLocal<RequestAttributes> requestAttributesHolder;
/*other fields and functions*/
}