方法

set()

该方法会检查当前调用线程,默认以该线程的Thread.currentThread()值作为键,来保存指定的值。

  1. public void set(T value) {
  2. Thread t = Thread.currentThread();
  3. ThreadLocalMap map = getMap(t);
  4. if (map != null)
  5. map.set(this, value);
  6. else
  7. createMap(t, value);
  8. }

get()

该方法会检查当前调用线程,默认以该线程的Thread.currentThread()值作为键,获取保存指定的值。

  1. public T get() {
  2. Thread t = Thread.currentThread();
  3. ThreadLocalMap map = getMap(t);
  4. if (map != null) {
  5. ThreadLocalMap.Entry e = map.getEntry(this);
  6. if (e != null) {
  7. @SuppressWarnings("unchecked")
  8. T result = (T)e.value;
  9. return result;
  10. }
  11. }
  12. return setInitialValue();
  13. }

eg

  1. package com.example.concurrent;
  2. /**
  3. * @Description:
  4. * @Author: baxiang
  5. * @Date: 2021/9/28.
  6. */
  7. public class ThreadLocalTest {
  8. static ThreadLocal<String> localVariable = new ThreadLocal<>();
  9. static void print(String str){
  10. //1.1 打印当前线程本地内存中localVariable变量的值
  11. System.out.println(str + ":" + localVariable.get());
  12. //1.2 清除当前线程本地内存中localVariable变量
  13. //localVariable.remove();
  14. }
  15. public static void main(String[] args) {
  16. //(3) 创建线程one
  17. Thread threadOne = new Thread(new Runnable() {
  18. @Override
  19. public void run() {
  20. //3.1 设置线程one中本地变量localVariable的值
  21. localVariable.set("threadOne local variable");
  22. //3.2 调用打印函数
  23. print("threadOne");
  24. //3.3打印本地变量值
  25. System.out.println("threadOne remove after" + ":" + localVariable.get());
  26. }
  27. });
  28. //(4) 创建线程two
  29. Thread threadTwo = new Thread(new Runnable() {
  30. @Override
  31. public void run() {
  32. //4.1 设置线程one中本地变量localVariable的值
  33. localVariable.set("threadTwo local variable");
  34. //4.2 调用打印函数
  35. print("threadTwo");
  36. //4.3打印本地变量值
  37. System.out.println("threadTwo remove after" + ":" + localVariable.get());
  38. }
  39. });
  40. //(5)启动线程
  41. threadOne.start();
  42. threadTwo.start();
  43. }
  44. }