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

 

posted @ 2017-12-27 21:24  栖息之鹰  阅读(618)  评论(0编辑  收藏  举报