ThreadLocal不好用?那是你没用对!

开发 前端
在 Java 中,如果要问哪个类使用简单,但用好最不简单?我想你的脑海中一定会浮现出一次词——“ThreadLocal”。

[[399225]]

本文转载自微信公众号「Java中文社群」,作者磊哥。转载本文请联系Java中文社群公众号。

在 Java 中,如果要问哪个类使用简单,但用好最不简单?我想你的脑海中一定会浮现出一次词——“ThreadLocal”。

确实如此,ThreadLocal 原本设计是为了解决并发时,线程共享变量的问题,但由于过度设计,如弱引用和哈希碰撞,从而导致它的理解难度大和使用成本高等问题。当然,如果稍有不慎还是导致脏数据、内存溢出、共享变量更新等问题,但即便如此,ThreadLocal 依旧有适合自己的使用场景,以及无可取代的价值,比如本文要介绍了这两种使用场景,除了 ThreadLocal 之外,还真没有合适的替代方案。

使用场景1:本地变量

我们以多线程格式化时间为例,来演示 ThreadLocal 的价值和作用,当我们在多个线程中格式化时间时,通常会这样操作。

① 2个线程格式化

当有 2 个线程进行时间格式化时,我们可以这样写:

  1. import java.text.SimpleDateFormat; 
  2. import java.util.Date
  3.  
  4. public class Test { 
  5.     public static void main(String[] args) throws InterruptedException { 
  6.         // 创建并启动线程1 
  7.         Thread t1 = new Thread(new Runnable() { 
  8.             @Override 
  9.             public void run() { 
  10.                 // 得到时间对象 
  11.                 Date date = new Date(1 * 1000); 
  12.                 // 执行时间格式化 
  13.                 formatAndPrint(date); 
  14.             } 
  15.         }); 
  16.         t1.start(); 
  17.         // 创建并启动线程2 
  18.         Thread t2 = new Thread(new Runnable() { 
  19.             @Override 
  20.             public void run() { 
  21.                 // 得到时间对象 
  22.                 Date date = new Date(2 * 1000); 
  23.                 // 执行时间格式化 
  24.                 formatAndPrint(date); 
  25.             } 
  26.         }); 
  27.         t2.start(); 
  28.     } 
  29.  
  30.     /** 
  31.      * 格式化并打印结果 
  32.      * @param date 时间对象 
  33.      */ 
  34.     private static void formatAndPrint(Date date) { 
  35.         // 格式化时间对象 
  36.         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss"); 
  37.         // 执行格式化 
  38.         String result = simpleDateFormat.format(date); 
  39.         // 打印最终结果 
  40.         System.out.println("时间:" + result); 
  41.     } 

以上程序的执行结果为:

上面的代码因为创建的线程数量并不多,所以我们可以给每个线程创建一个私有对象 SimpleDateFormat 来进行时间格式化。

② 10个线程格式化

当线程的数量从 2 个升级为 10 个时,我们可以使用 for 循环来创建多个线程执行时间格式化,具体实现代码如下:

  1. import java.text.SimpleDateFormat; 
  2. import java.util.Date
  3.  
  4. public class Test { 
  5.     public static void main(String[] args) throws InterruptedException { 
  6.         for (int i = 0; i < 10; i++) { 
  7.             int finalI = i; 
  8.             // 创建线程 
  9.             Thread thread = new Thread(new Runnable() { 
  10.                 @Override 
  11.                 public void run() { 
  12.                     // 得到时间对象 
  13.                     Date date = new Date(finalI * 1000); 
  14.                     // 执行时间格式化 
  15.                     formatAndPrint(date); 
  16.                 } 
  17.             }); 
  18.             // 启动线程 
  19.             thread.start(); 
  20.         } 
  21.     } 
  22.     /** 
  23.      * 格式化并打印时间 
  24.      * @param date 时间对象 
  25.      */ 
  26.     private static void formatAndPrint(Date date) { 
  27.         // 格式化时间对象 
  28.         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss"); 
  29.         // 执行格式化 
  30.         String result = simpleDateFormat.format(date); 
  31.         // 打印最终结果 
  32.         System.out.println("时间:" + result); 
  33.     } 

以上程序的执行结果为:

从上述结果可以看出,虽然此时创建的线程数和 SimpleDateFormat 的数量不算少,但程序还是可以正常运行的。

③ 1000个线程格式化

然而当我们将线程的数量从 10 个变成 1000 个的时候,我们就不能单纯的使用 for 循环来创建 1000 个线程的方式来解决问题了,因为这样频繁的新建和销毁线程会造成大量的系统开销和线程过度争抢 CPU 资源的问题。

所以经过一番思考后,我们决定使用线程池来执行这 1000 次的任务,因为线程池可以复用线程资源,无需频繁的新建和销毁线程,也可以通过控制线程池中线程的数量来避免过多线程所导致的 CPU 资源过度争抢和线程频繁切换所造成的性能问题,而且我们可以将 SimpleDateFormat 提升为全局变量,从而避免每次执行都要新建 SimpleDateFormat 的问题,于是我们写下了这样的代码:

  1. import java.text.SimpleDateFormat; 
  2. import java.util.Date
  3. import java.util.concurrent.LinkedBlockingQueue; 
  4. import java.util.concurrent.ThreadPoolExecutor; 
  5. import java.util.concurrent.TimeUnit; 
  6.  
  7. public class App { 
  8.     // 时间格式化对象 
  9.     private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss"); 
  10.  
  11.     public static void main(String[] args) throws InterruptedException { 
  12.         // 创建线程池执行任务 
  13.         ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 10, 60, 
  14.                 TimeUnit.SECONDS, new LinkedBlockingQueue<>(1000)); 
  15.         for (int i = 0; i < 1000; i++) { 
  16.             int finalI = i; 
  17.             // 执行任务 
  18.             threadPool.execute(new Runnable() { 
  19.                 @Override 
  20.                 public void run() { 
  21.                     // 得到时间对象 
  22.                     Date date = new Date(finalI * 1000); 
  23.                     // 执行时间格式化 
  24.                     formatAndPrint(date); 
  25.                 } 
  26.             }); 
  27.         } 
  28.         // 线程池执行完任务之后关闭 
  29.         threadPool.shutdown(); 
  30.     } 
  31.  
  32.     /** 
  33.      * 格式化并打印时间 
  34.      * @param date 时间对象 
  35.      */ 
  36.     private static void formatAndPrint(Date date) { 
  37.         // 执行格式化 
  38.         String result = simpleDateFormat.format(date); 
  39.         // 打印最终结果 
  40.         System.out.println("时间:" + result); 
  41.     } 

以上程序的执行结果为:

当我们怀着无比喜悦的心情去运行程序的时候,却发现意外发生了,这样写代码竟然会出现线程安全的问题。从上述结果可以看出,程序的打印结果竟然有重复内容的,正确的情况应该是没有重复的时间才对。

PS:所谓的线程安全问题是指:在多线程的执行中,程序的执行结果与预期结果不相符的情况。

a) 线程安全问题分析

为了找到问题所在,我们尝试查看 SimpleDateFormat 中 format 方法的源码来排查一下问题,format 源码如下:

  1. private StringBuffer format(Date date, StringBuffer toAppendTo, 
  2.                                 FieldDelegate delegate) { 
  3.     // 注意此行代码 
  4.     calendar.setTime(date); 
  5.  
  6.     boolean useDateFormatSymbols = useDateFormatSymbols(); 
  7.  
  8.     for (int i = 0; i < compiledPattern.length; ) { 
  9.         int tag = compiledPattern[i] >>> 8; 
  10.         int count = compiledPattern[i++] & 0xff; 
  11.         if (count == 255) { 
  12.             count = compiledPattern[i++] << 16; 
  13.             count |= compiledPattern[i++]; 
  14.         } 
  15.  
  16.         switch (tag) { 
  17.             case TAG_QUOTE_ASCII_CHAR: 
  18.                 toAppendTo.append((char)count); 
  19.                 break; 
  20.  
  21.             case TAG_QUOTE_CHARS: 
  22.                 toAppendTo.append(compiledPattern, i, count); 
  23.                 i += count
  24.                 break; 
  25.  
  26.             default
  27.                 subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols); 
  28.                 break; 
  29.         } 
  30.     } 
  31.     return toAppendTo; 

从上述源码可以看出,在执行 SimpleDateFormat.format 方法时,会使用 calendar.setTime 方法将输入的时间进行转换,那么我们想想一下这样的场景:

  1. 线程 1 执行了 calendar.setTime(date) 方法,将用户输入的时间转换成了后面格式化时所需要的时间;
  2. 线程 1 暂停执行,线程 2 得到 CPU 时间片开始执行;
  3. 线程 2 执行了 calendar.setTime(date) 方法,对时间进行了修改;
  4. 线程 2 暂停执行,线程 1 得出 CPU 时间片继续执行,因为线程 1 和线程 2 使用的是同一对象,而时间已经被线程 2 修改了,所以此时当线程 1 继续执行的时候就会出现线程安全的问题了。

正常的情况下,程序的执行是这样的:

非线程安全的执行流程是这样的:

b) 解决线程安全问题:加锁

当出现线程安全问题时,我们想到的第一解决方案就是加锁,具体的实现代码如下:

  1. import java.text.SimpleDateFormat; 
  2. import java.util.Date
  3. import java.util.concurrent.LinkedBlockingQueue; 
  4. import java.util.concurrent.ThreadPoolExecutor; 
  5. import java.util.concurrent.TimeUnit; 
  6.  
  7. public class App { 
  8.     // 时间格式化对象 
  9.     private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss"); 
  10.  
  11.     public static void main(String[] args) throws InterruptedException { 
  12.         // 创建线程池执行任务 
  13.         ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 10, 60, 
  14.                 TimeUnit.SECONDS, new LinkedBlockingQueue<>(1000)); 
  15.         for (int i = 0; i < 1000; i++) { 
  16.             int finalI = i; 
  17.             // 执行任务 
  18.             threadPool.execute(new Runnable() { 
  19.                 @Override 
  20.                 public void run() { 
  21.                     // 得到时间对象 
  22.                     Date date = new Date(finalI * 1000); 
  23.                     // 执行时间格式化 
  24.                     formatAndPrint(date); 
  25.                 } 
  26.             }); 
  27.         } 
  28.         // 线程池执行完任务之后关闭 
  29.         threadPool.shutdown(); 
  30.     } 
  31.  
  32.     /** 
  33.      * 格式化并打印时间 
  34.      * @param date 时间对象 
  35.      */ 
  36.     private static void formatAndPrint(Date date) { 
  37.         // 执行格式化 
  38.         String result = null
  39.         // 加锁 
  40.         synchronized (App.class) { 
  41.             result = simpleDateFormat.format(date); 
  42.         } 
  43.         // 打印最终结果 
  44.         System.out.println("时间:" + result); 
  45.     } 

以上程序的执行结果为:

从上述结果可以看出,使用了 synchronized 加锁之后程序就可以正常的执行了。

加锁的缺点

加锁的方式虽然可以解决线程安全的问题,但同时也带来了新的问题,当程序加锁之后,所有的线程必须排队执行某些业务才行,这样无形中就降低了程序的运行效率了。

有没有既能解决线程安全问题,又能提高程序的执行速度的解决方案呢?

答案是:有的,这个时候 ThreadLocal就要上场了。

c) 解决线程安全问题:ThreadLocal

1.ThreadLocal 介绍

ThreadLocal 从字面的意思来理解是线程本地变量的意思,也就是说它是线程中的私有变量,每个线程只能使用自己的变量。

以上面线程池格式化时间为例,当线程池中有 10 个线程时,SimpleDateFormat 会存入 ThreadLocal 中,它也只会创建 10 个对象,即使要执行 1000 次时间格式化任务,依然只会新建 10 个 SimpleDateFormat 对象,每个线程调用自己的 ThreadLocal 变量。

2.ThreadLocal 基础使用

ThreadLocal 常用的核心方法有三个:

  1. set 方法:用于设置线程独立变量副本。没有 set 操作的 ThreadLocal 容易引起脏数据。
  2. get 方法:用于获取线程独立变量副本。没有 get 操作的 ThreadLocal 对象没有意义。
  3. remove 方法:用于移除线程独立变量副本。没有 remove 操作容易引起内存泄漏。

ThreadLocal 所有方法如下图所示:

官方说明文档:https://docs.oracle.com/javase/8/docs/api/

ThreadLocal 基础用法如下:

  1. /** 
  2.  * @公众号:Java中文社群 
  3.  */ 
  4. public class ThreadLocalExample { 
  5.     // 创建一个 ThreadLocal 对象 
  6.     private static ThreadLocal<String> threadLocal = new ThreadLocal<>(); 
  7.  
  8.     public static void main(String[] args) { 
  9.         // 线程执行任务 
  10.         Runnable runnable = new Runnable() { 
  11.             @Override 
  12.             public void run() { 
  13.                 String threadName = Thread.currentThread().getName(); 
  14.                 System.out.println(threadName + " 存入值:" + threadName); 
  15.                 // 在 ThreadLocal 中设置值 
  16.                 threadLocal.set(threadName); 
  17.                 // 执行方法,打印线程中设置的值 
  18.                 print(threadName); 
  19.             } 
  20.         }; 
  21.         // 创建并启动线程 1 
  22.         new Thread(runnable, "MyThread-1").start(); 
  23.         // 创建并启动线程 2 
  24.         new Thread(runnable, "MyThread-2").start(); 
  25.     } 
  26.  
  27.     /** 
  28.      * 打印线程中的 ThreadLocal 值 
  29.      * @param threadName 线程名称 
  30.      */ 
  31.     private static void print(String threadName) { 
  32.         try { 
  33.             // 得到 ThreadLocal 中的值 
  34.             String result = threadLocal.get(); 
  35.             // 打印结果 
  36.             System.out.println(threadName + " 取出值:" + result); 
  37.         } finally { 
  38.             // 移除 ThreadLocal 中的值(防止内存溢出) 
  39.             threadLocal.remove(); 
  40.         } 
  41.     } 

以上程序的执行结果为:

从上述结果可以看出,每个线程只会读取到属于自己的 ThreadLocal 值。

3.ThreadLocal 高级用法

① 初始化:initialValue

  1. public class ThreadLocalByInitExample { 
  2.     // 定义 ThreadLocal 
  3.     private static ThreadLocal<String> threadLocal = new ThreadLocal(){ 
  4.         @Override 
  5.         protected String initialValue() { 
  6.             System.out.println("执行 initialValue() 方法"); 
  7.             return "默认值"
  8.         } 
  9.     }; 
  10.  
  11.     public static void main(String[] args) { 
  12.         // 线程执行任务 
  13.         Runnable runnable = new Runnable() { 
  14.             @Override 
  15.             public void run() { 
  16.                 // 执行方法,打印线程中数据(未设置值打印) 
  17.                 print(threadName); 
  18.             } 
  19.         }; 
  20.         // 创建并启动线程 1 
  21.         new Thread(runnable, "MyThread-1").start(); 
  22.         // 创建并启动线程 2 
  23.         new Thread(runnable, "MyThread-2").start(); 
  24.     } 
  25.  
  26.     /** 
  27.      * 打印线程中的 ThreadLocal 值 
  28.      * @param threadName 线程名称 
  29.      */ 
  30.     private static void print(String threadName) { 
  31.         // 得到 ThreadLocal 中的值 
  32.         String result = threadLocal.get(); 
  33.         // 打印结果 
  34.         System.out.println(threadName + " 得到值:" + result); 
  35.     } 

以上程序的执行结果为:

当使用了 #threadLocal.set 方法之后,initialValue 方法就不会被执行了,如下代码所示:

  1. public class ThreadLocalByInitExample { 
  2.     // 定义 ThreadLocal 
  3.     private static ThreadLocal<String> threadLocal = new ThreadLocal() { 
  4.         @Override 
  5.         protected String initialValue() { 
  6.             System.out.println("执行 initialValue() 方法"); 
  7.             return "默认值"
  8.         } 
  9.     }; 
  10.  
  11.     public static void main(String[] args) { 
  12.         // 线程执行任务 
  13.         Runnable runnable = new Runnable() { 
  14.             @Override 
  15.             public void run() { 
  16.                 String threadName = Thread.currentThread().getName(); 
  17.                 System.out.println(threadName + " 存入值:" + threadName); 
  18.                 // 在 ThreadLocal 中设置值 
  19.                 threadLocal.set(threadName); 
  20.                 // 执行方法,打印线程中设置的值 
  21.                 print(threadName); 
  22.             } 
  23.         }; 
  24.         // 创建并启动线程 1 
  25.         new Thread(runnable, "MyThread-1").start(); 
  26.         // 创建并启动线程 2 
  27.         new Thread(runnable, "MyThread-2").start(); 
  28.     } 
  29.  
  30.     /** 
  31.      * 打印线程中的 ThreadLocal 值 
  32.      * @param threadName 线程名称 
  33.      */ 
  34.     private static void print(String threadName) { 
  35.         try { 
  36.             // 得到 ThreadLocal 中的值 
  37.             String result = threadLocal.get(); 
  38.             // 打印结果 
  39.             System.out.println(threadName + "取出值:" + result); 
  40.         } finally { 
  41.             // 移除 ThreadLocal 中的值(防止内存溢出) 
  42.             threadLocal.remove(); 
  43.         } 
  44.     } 

以上程序的执行结果为:

为什么 set 之后,初始化代码就不执行了?

要理解这个问题,需要从 ThreadLocal.get() 方法的源码中得到答案,因为初始化方法 initialValue 在 ThreadLocal 创建时并不会立即执行,而是在调用了 get 方法只会才会执行,测试代码如下:

  1. import java.util.Date
  2.  
  3. public class ThreadLocalByInitExample { 
  4.     // 定义 ThreadLocal 
  5.     private static ThreadLocal<String> threadLocal = new ThreadLocal() { 
  6.         @Override 
  7.         protected String initialValue() { 
  8.             System.out.println("执行 initialValue() 方法 " + new Date()); 
  9.             return "默认值"
  10.         } 
  11.     }; 
  12.     public static void main(String[] args) { 
  13.         // 线程执行任务 
  14.         Runnable runnable = new Runnable() { 
  15.             @Override 
  16.             public void run() { 
  17.                 // 得到当前线程名称 
  18.                 String threadName = Thread.currentThread().getName(); 
  19.                 // 执行方法,打印线程中设置的值 
  20.                 print(threadName); 
  21.             } 
  22.         }; 
  23.         // 创建并启动线程 1 
  24.         new Thread(runnable, "MyThread-1").start(); 
  25.         // 创建并启动线程 2 
  26.         new Thread(runnable, "MyThread-2").start(); 
  27.     } 
  28.  
  29.     /** 
  30.      * 打印线程中的 ThreadLocal 值 
  31.      * @param threadName 线程名称 
  32.      */ 
  33.     private static void print(String threadName) { 
  34.         System.out.println("进入 print() 方法 " + new Date()); 
  35.         try { 
  36.             // 休眠 1s 
  37.             Thread.sleep(1000); 
  38.         } catch (InterruptedException e) { 
  39.             e.printStackTrace(); 
  40.         } 
  41.         // 得到 ThreadLocal 中的值 
  42.         String result = threadLocal.get(); 
  43.         // 打印结果 
  44.         System.out.println(String.format("%s 取得值:%s %s"
  45.                 threadName, result, new Date())); 
  46.     } 

以上程序的执行结果为:

从上述打印的时间可以看出:initialValue 方法并不是在 ThreadLocal 创建时执行的,而是在调用 Thread.get 方法时才执行的。

接下来来看 Threadlocal.get 源码的实现:

  1. public T get() { 
  2.     // 得到当前的线程 
  3.     Thread t = Thread.currentThread(); 
  4.     ThreadLocalMap map = getMap(t); 
  5.     // 判断 ThreadLocal 中是否有数据 
  6.     if (map != null) { 
  7.         ThreadLocalMap.Entry e = map.getEntry(this); 
  8.         if (e != null) { 
  9.             @SuppressWarnings("unchecked"
  10.             T result = (T)e.value; 
  11.             // 有 set 值,直接返回数据 
  12.             return result; 
  13.         } 
  14.     } 
  15.     // 执行初始化方法【重点关注】 
  16.     return setInitialValue(); 
  17. private T setInitialValue() { 
  18.     // 执行初始化方法【重点关注】 
  19.     T value = initialValue(); 
  20.     Thread t = Thread.currentThread(); 
  21.     ThreadLocalMap map = getMap(t); 
  22.     if (map != null
  23.         map.set(this, value); 
  24.     else 
  25.         createMap(t, value); 
  26.     return value; 

从上述源码可以看出,当 ThreadLocal 中有值时会直接返回值 e.value,只有 Threadlocal 中没有任何值时才会执行初始化方法 initialValue。

注意事项—类型必须保持一致

注意在使用 initialValue 时,返回值的类型要和 ThreadLoca 定义的数据类型保持一致,如下图所示:

如果数据不一致就会造成 ClassCaseException 类型转换异常,如下图所示:

② 初始化2:withInitial

  1. import java.util.function.Supplier; 
  2.  
  3. public class ThreadLocalByInitExample { 
  4.     // 定义 ThreadLocal 
  5.     private static ThreadLocal<String> threadLocal = 
  6.             ThreadLocal.withInitial(new Supplier<String>() { 
  7.                 @Override 
  8.                 public String get() { 
  9.                     System.out.println("执行 withInitial() 方法"); 
  10.                     return "默认值"
  11.                 } 
  12.             }); 
  13.     public static void main(String[] args) { 
  14.         // 线程执行任务 
  15.         Runnable runnable = new Runnable() { 
  16.             @Override 
  17.             public void run() { 
  18.                 String threadName = Thread.currentThread().getName(); 
  19.                 // 执行方法,打印线程中设置的值 
  20.                 print(threadName); 
  21.             } 
  22.         }; 
  23.         // 创建并启动线程 1 
  24.         new Thread(runnable, "MyThread-1").start(); 
  25.         // 创建并启动线程 2 
  26.         new Thread(runnable, "MyThread-2").start(); 
  27.     } 
  28.  
  29.     /** 
  30.      * 打印线程中的 ThreadLocal 值 
  31.      * @param threadName 线程名称 
  32.      */ 
  33.     private static void print(String threadName) { 
  34.         // 得到 ThreadLocal 中的值 
  35.         String result = threadLocal.get(); 
  36.         // 打印结果 
  37.         System.out.println(threadName + " 得到值:" + result); 
  38.     } 

以上程序的执行结果为:

通过上述的代码发现,withInitial 方法的使用好和 initialValue 好像没啥区别,那为啥还要造出两个类似的方法呢?客官莫着急,继续往下看。

③ 更简洁的 withInitial 使用

withInitial 方法的优势在于可以更简单的实现变量初始化,如下代码所示:

  1. public class ThreadLocalByInitExample { 
  2.     // 定义 ThreadLocal 
  3.     private static ThreadLocal<String> threadLocal = ThreadLocal.withInitial(() -> "默认值"); 
  4.     public static void main(String[] args) { 
  5.         // 线程执行任务 
  6.         Runnable runnable = new Runnable() { 
  7.             @Override 
  8.             public void run() { 
  9.                 String threadName = Thread.currentThread().getName(); 
  10.                 // 执行方法,打印线程中设置的值 
  11.                 print(threadName); 
  12.             } 
  13.         }; 
  14.         // 创建并启动线程 1 
  15.         new Thread(runnable, "MyThread-1").start(); 
  16.         // 创建并启动线程 2 
  17.         new Thread(runnable, "MyThread-2").start(); 
  18.     } 
  19.  
  20.     /** 
  21.      * 打印线程中的 ThreadLocal 值 
  22.      * @param threadName 线程名称 
  23.      */ 
  24.     private static void print(String threadName) { 
  25.         // 得到 ThreadLocal 中的值 
  26.         String result = threadLocal.get(); 
  27.         // 打印结果 
  28.         System.out.println(threadName + " 得到值:" + result); 
  29.     } 

以上程序的执行结果为:

4.ThreadLocal 版时间格式化

了解了 ThreadLocal 的使用之后,我们回到本文的主题,接下来我们将使用 ThreadLocal 来实现 1000 个时间的格式化,具体实现代码如下:

  1. import java.text.SimpleDateFormat; 
  2. import java.util.Date
  3. import java.util.concurrent.LinkedBlockingQueue; 
  4. import java.util.concurrent.ThreadPoolExecutor; 
  5. import java.util.concurrent.TimeUnit; 
  6.  
  7. public class MyThreadLocalByDateFormat { 
  8.     // 创建 ThreadLocal 并设置默认值 
  9.     private static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = 
  10.             ThreadLocal.withInitial(() -> new SimpleDateFormat("mm:ss")); 
  11.  
  12.     public static void main(String[] args) { 
  13.         // 创建线程池执行任务 
  14.         ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 10, 60, 
  15.                 TimeUnit.SECONDS, new LinkedBlockingQueue<>(1000)); 
  16.         // 执行任务 
  17.         for (int i = 0; i < 1000; i++) { 
  18.             int finalI = i; 
  19.             // 执行任务 
  20.             threadPool.execute(new Runnable() { 
  21.                 @Override 
  22.                 public void run() { 
  23.                     // 得到时间对象 
  24.                     Date date = new Date(finalI * 1000); 
  25.                     // 执行时间格式化 
  26.                     formatAndPrint(date); 
  27.                 } 
  28.             }); 
  29.         } 
  30.         // 线程池执行完任务之后关闭 
  31.         threadPool.shutdown(); 
  32.         // 线程池执行完任务之后关闭 
  33.         threadPool.shutdown(); 
  34.     } 
  35.     /** 
  36.      * 格式化并打印时间 
  37.      * @param date 时间对象 
  38.      */ 
  39.     private static void formatAndPrint(Date date) { 
  40.         // 执行格式化 
  41.         String result = dateFormatThreadLocal.get().format(date); 
  42.         // 打印最终结果 
  43.         System.out.println("时间:" + result); 
  44.     } 

以上程序的执行结果为:

从上述结果可以看出,使用 ThreadLocal 也可以解决线程并发问题,并且避免了代码加锁排队执行的问题。

使用场景2:跨类传递数据

除了上面的使用场景之外,我们还可以使用 ThreadLocal 来实现线程中跨类、跨方法的数据传递。比如登录用户的 User 对象信息,我们需要在不同的子系统中多次使用,如果使用传统的方式,我们需要使用方法传参和返回值的方式来传递 User 对象,然而这样就无形中造成了类和类之间,甚至是系统和系统之间的相互耦合了,所以此时我们可以使用 ThreadLocal 来实现 User 对象的传递。

确定了方案之后,接下来我们来实现具体的业务代码。我们可以先在主线程中构造并初始化一个 User 对象,并将此 User 对象存储在 ThreadLocal 中,存储完成之后,我们就可以在同一个线程的其他类中,如仓储类或订单类中直接获取并使用 User 对象了,具体实现代码如下。

主线程中的业务代码:

  1. public class ThreadLocalByUser { 
  2.     public static void main(String[] args) { 
  3.         // 初始化用户信息 
  4.         User user = new User("Java"); 
  5.         // 将 User 对象存储在 ThreadLocal 中 
  6.         UserStorage.setUser(user); 
  7.         // 调用订单系统 
  8.         OrderSystem orderSystem = new OrderSystem(); 
  9.         // 添加订单(方法内获取用户信息) 
  10.         orderSystem.add(); 
  11.         // 调用仓储系统 
  12.         RepertorySystem repertory = new RepertorySystem(); 
  13.         // 减库存(方法内获取用户信息) 
  14.         repertory.decrement(); 
  15.     } 

User 实体类:

  1. /** 
  2.  * 用户实体类 
  3.  */ 
  4. class User { 
  5.     public User(String name) { 
  6.         this.name = name
  7.     } 
  8.     private String name
  9.     public String getName() { 
  10.         return name
  11.     } 
  12.     public void setName(String name) { 
  13.         this.name = name
  14.     } 

ThreadLocal 操作类:

  1. /** 
  2.  * 用户信息存储类 
  3.  */ 
  4. class UserStorage { 
  5.     // 用户信息 
  6.     public static ThreadLocal<UserUSER = new ThreadLocal(); 
  7.  
  8.     /** 
  9.      * 存储用户信息 
  10.      * @param user 用户数据 
  11.      */ 
  12.     public static void setUser(User user) { 
  13.         USER.set(user); 
  14.     } 

* 订单类

  1. /** 
  2.  * 订单类 
  3.  */ 
  4. class OrderSystem { 
  5.     /** 
  6.      * 订单添加方法 
  7.      */ 
  8.     public void add() { 
  9.         // 得到用户信息 
  10.         User user = UserStorage.USER.get(); 
  11.         // 业务处理代码(忽略)... 
  12.         System.out.println(String.format("订单系统收到用户:%s 的请求。"
  13.                 user.getName())); 
  14.     } 

仓储类:

  1. /** 
  2.  * 仓储类 
  3.  */ 
  4. class RepertorySystem { 
  5.     /** 
  6.      * 减库存方法 
  7.      */ 
  8.     public void decrement() { 
  9.         // 得到用户信息 
  10.         User user = UserStorage.USER.get(); 
  11.         // 业务处理代码(忽略)... 
  12.         System.out.println(String.format("仓储系统收到用户:%s 的请求。"
  13.                 user.getName())); 
  14.     } 

以上程序的最终执行结果:

从上述结果可以看出,当我们在主线程中先初始化了 User 对象之后,订单类和仓储类无需进行任何的参数传递也可以正常获得 User 对象了,从而实现了一个线程中,跨类和跨方法的数据传递。

总结

使用 ThreadLocal 可以创建线程私有变量,所以不会导致线程安全问题,同时使用 ThreadLocal 还可以避免因为引入锁而造成线程排队执行所带来的性能消耗;再者使用 ThreadLocal 还可以实现一个线程内跨类、跨方法的数据传递。

参考 & 鸣谢

《码出高效:Java开发手册》

《Java 并发编程 78 讲》

 

责任编辑:武晓燕 来源: Java中文社群
相关推荐

2019-05-09 18:24:28

Windows 10Windows操作系统

2021-12-22 23:19:05

Windows 10Windows微软

2014-11-04 10:15:28

Android

2023-03-13 00:21:21

调试器断点开发者

2014-10-20 10:53:13

ArubaWi-Fi无线网络

2019-10-31 16:10:48

Windows 10Windows技巧

2021-02-17 21:33:39

路由器产品网络

2021-05-10 07:35:11

SwaggeYApi部署

2014-02-21 10:20:40

2020-10-19 08:14:58

Windows10

2023-10-25 16:36:06

数字化转型IT系统

2020-03-19 14:30:13

Windows触摸板MacBook

2021-08-16 13:44:37

手机电子日本

2022-07-29 08:40:20

设计模式责任链场景

2021-04-27 22:38:41

代码开发前端

2023-11-28 12:25:02

多线程安全

2020-01-17 20:00:25

SQL函数数据库

2016-10-10 09:15:10

Windows 10工具桌面

2021-07-28 06:46:25

Windows 操作系统微软

2021-03-19 05:58:31

APP手机热点推荐
点赞
收藏

51CTO技术栈公众号