您好,欢迎访问一九零五行业门户网

ThreadLocal是什么?ThreadLocal的原理分析

本篇文章给大家带来的内容是关于threadlocal是什么?threadlocal的原理分析,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
1、 threadlocal是什么
threadlocal提供线程局部变量。这些变量与普通的变量不同之处在于,每个访问这种变量的线程(通过它的get或set方法)都有自己的、独立初始化的变量副本。
threadlocal实例通常是希望将状态关联到一个线程的类的私有静态字段(比如,user id 或者 transaction id 等等)。
(画外音:这段话表达了三个意思
1、threadlocal是一种变量类型,我们称之为“线程局部变量”。
2、每个线程访问这种变量的时候都会创建该变量的副本,这个变量副本为线程私有。
3、threadlocal类型的变量一般用private static加以修饰。)
例如,下面的例子中这个类为每个线程生成唯一标识。一个线程的id是它第一次调用threadid.get()方法指定的。
package com.cjs.example;import java.util.concurrent.atomic.atomicinteger;public class threadid { private static final atomicinteger nextid = new atomicinteger(0); private static final threadlocal<integer> threadid = new threadlocal<integer>() { @override protected integer initialvalue() { return nextid.getandincrement(); } }; public static int get() { return threadid.get(); } public static void main(string[] args) { for (int i = 0; i < 10; i++) { new thread(new runnable() { @override public void run() { system.out.println(thread.currentthread().getid()); } }).start(); } }}
2. threadlocal主要操作
/** * 返回当前线程对threadlocal变量的“初始值” * 这个方法将在线程第一次访问变量(通过调用get方法)时被调用,如果之前已经调用过了就不会再调了 * * @return the initial value for this thread-local */protected t initialvalue() { return null;}/** * 设置当前线程的threadlocal变量的副本为指定的值 * * @param value the value to be stored in the current thread's copy of this thread-local. */public void set(t value) { thread t = thread.currentthread(); threadlocalmap map = getmap(t); if (map != null) map.set(this, value); else createmap(t, value);}/** * 返回当前线程的threadlocal变量副本的值 * * @return the current thread's value of this thread-local */public t get() { thread t = thread.currentthread(); threadlocalmap map = getmap(t); if (map != null) { threadlocalmap.entry e = map.getentry(this); if (e != null) { @suppresswarnings("unchecked") t result = (t)e.value; return result; } } return setinitialvalue();}/** * 删除当前线程的threadlocal变量副本的值 */public void remove() { threadlocalmap m = getmap(thread.currentthread()); if (m != null) m.remove(this);}
3.  阅读源码
3.1.  set方法
可以看到,threadlocalmap底层是一个数组,数组中元素类型是entry类型
set操作是向当前线程的threadlocal.threadlocalmap类型的成员变量threadlocals中设置值,key是this,value是我们指定的值
注意,这里传的this代表的是那个threadlocal类型的变量(或者说叫对象)
也就是说,每个线程都维护了一个threadlocal.threadlocalmap类型的对象,而set操作其实就是以threadlocal变量为key,以我们指定的值为value,最后将这个键值对封装成entry对象放到该线程的threadlocal.threadlocalmap对象中。每个threadlocal变量在该线程中都是threadlocal.threadlocalmap对象中的一个entry。既然每个threadlocal变量都对应threadlocal.threadlocalmap中的一个元素,那么就可以对这些元素进行读写删除操作。
3.2.  get方法
get()方法就是从当前线程的threadlocal.threadlocalmap对象中取出对应的threadlocal变量所对应的值
同理,remove()方法就是清除这个值
用图形表示的话,大概是这样的:
或者是这样的:
4.  threadlocal使用场景
在线程生命周期内传值
最后,一切都归功于threadlocalmap
以上就是threadlocal是什么?threadlocal的原理分析的详细内容。
其它类似信息

推荐信息