Java中的ThreadLocal使用

Posted 栖息之鹰

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java中的ThreadLocal使用相关的知识,希望对你有一定的参考价值。

ThreadLocal用于下面的场景:

1. 不允许多个线程同时访问的资源

2. 单个线程存活过程只使用一个实例

 

官方定义如下:

This class provides thread-local variables. 
These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable.
ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).

 

使用例子(官方实例:每个线程有自己单独的ID,而且这个ID随着新的线程添加保持自增):

 import java.util.concurrent.atomic.AtomicInteger;

 public class ThreadId {
     // Atomic integer containing the next thread ID to be assigned
     private static final AtomicInteger nextId = new AtomicInteger(0);

     // Thread local variable containing each thread‘s ID
     private static final ThreadLocal<Integer> threadId =
         new ThreadLocal<Integer>() {
             @Override protected Integer initialValue() {
                 return nextId.getAndIncrement();
         }
     };

     // Returns the current thread‘s unique ID, assigning it if necessary
     public static int get() {
         return threadId.get();
     }
 }

 

本文不再对源码详解,感兴趣的同学可以自己读解源码。

参考:

https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html

 

以上是关于Java中的ThreadLocal使用的主要内容,如果未能解决你的问题,请参考以下文章

Java 8 ThreadLocal 源码解析

java 中的 ThreadLocal

14Java并发性和多线程-Java ThreadLocal

Java中的线程本地变量ThreadLocal

Java中的线程本地变量ThreadLocal

MyBatis基础:使用java提供的ThreadLocal类优化代码