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

    ---栖息之鹰(一个外表懒洋洋的内心有激情的程序员) 此博客为笔者原著,转载时请注明出处,谢谢!
  • 相关阅读:
    python-socket1
    python-网络编程
    linux-常用指令3
    linux-vim/编辑器
    linux-常用指令2
    linux-常用指令1
    MySQL 练习题
    33 python 并发编程之IO模型
    32 python 并发编程之协程
    31 python下实现并发编程
  • 原文地址:https://www.cnblogs.com/roostinghawk/p/8127763.html
Copyright © 2011-2022 走看看