zoukankan      html  css  js  c++  java
  • 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

    ---栖息之鹰(一个外表懒洋洋的内心有激情的程序员) 此博客为笔者原著,转载时请注明出处,谢谢!
  • 相关阅读:
    平台架构设计及市场分析
    编写jQuery插件
    分布式锁
    初探12306售票算法(一)- 理论(转)
    年后跳槽如何准备?(转)
    therefore/so/hence/then/accordingly/Thus
    ignore,neglect,omit,overlook
    OOA/OOD/OOP(转)
    SQL Server里的 ISNULL 与 NULLIF
    稀疏矩阵
  • 原文地址:https://www.cnblogs.com/roostinghawk/p/8127763.html
Copyright © 2011-2022 走看看