方法
set()
该方法会检查当前调用线程,默认以该线程的Thread.currentThread()
值作为键,来保存指定的值。
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
get()
该方法会检查当前调用线程,默认以该线程的Thread.currentThread()
值作为键,获取保存指定的值。
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();
}
eg
package com.example.concurrent;
/**
* @Description:
* @Author: baxiang
* @Date: 2021/9/28.
*/
public class ThreadLocalTest {
static ThreadLocal<String> localVariable = new ThreadLocal<>();
static void print(String str){
//1.1 打印当前线程本地内存中localVariable变量的值
System.out.println(str + ":" + localVariable.get());
//1.2 清除当前线程本地内存中localVariable变量
//localVariable.remove();
}
public static void main(String[] args) {
//(3) 创建线程one
Thread threadOne = new Thread(new Runnable() {
@Override
public void run() {
//3.1 设置线程one中本地变量localVariable的值
localVariable.set("threadOne local variable");
//3.2 调用打印函数
print("threadOne");
//3.3打印本地变量值
System.out.println("threadOne remove after" + ":" + localVariable.get());
}
});
//(4) 创建线程two
Thread threadTwo = new Thread(new Runnable() {
@Override
public void run() {
//4.1 设置线程one中本地变量localVariable的值
localVariable.set("threadTwo local variable");
//4.2 调用打印函数
print("threadTwo");
//4.3打印本地变量值
System.out.println("threadTwo remove after" + ":" + localVariable.get());
}
});
//(5)启动线程
threadOne.start();
threadTwo.start();
}
}