日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

为什么jdk源码推荐ThreadLocal使用static

發布時間:2023/11/27 生活经验 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 为什么jdk源码推荐ThreadLocal使用static 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

ThreadLocal是線程私有變量,本身是解決多線程環境線程安全,可以說單線程實際上沒必要使用。

既然多線程環境本身不使用static,那么又怎么會線程不安全。所以這個問題本身并不是問題,只是有人沒有理解ThreadLocal的真正使用場景,所以有此疑問。

看看jdk源碼推薦ThreadLocal使用static吧:

/*** This class provides thread-local variables.  These variables differ from* their normal counterparts in that each thread that accesses one (via its* {@code get} or {@code set} method) has its own, independently initialized* copy of the variable.  {@code 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).** <p>For example, the class below generates unique identifiers local to each* thread.* A thread's id is assigned the first time it invokes {@code ThreadId.get()}* and remains unchanged on subsequent calls.* <pre>* 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&lt;Integer&gt; threadId =*         new ThreadLocal&lt;Integer&gt;() {*             &#64;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();*     }* }* </pre>* <p>Each thread holds an implicit reference to its copy of a thread-local* variable as long as the thread is alive and the {@code ThreadLocal}* instance is accessible; after a thread goes away, all of its copies of* thread-local instances are subject to garbage collection (unless other* references to these copies exist).** @author  Josh Bloch and Doug Lea* @since   1.2*/
public class ThreadLocal<T> {/*** ThreadLocals rely on per-thread linear-probe hash maps attached* to each thread (Thread.threadLocals and* inheritableThreadLocals).  The ThreadLocal objects act as keys,* searched via threadLocalHashCode.  This is a custom hash code* (useful only within ThreadLocalMaps) that eliminates collisions* in the common case where consecutively constructed ThreadLocals* are used by the same threads, while remaining well-behaved in* less common cases.*/

這個是Josh Bloch和Doug Lea寫的,再看看他們的著作:《Java并發編程實戰》

再看看jdk中的官方文檔:?

已經說的很明白了,再看看其他答案吧:

?

按照ThreadLocal類的定義

此類提供線程局部變量。這些變量與普通變量不同,每個訪問一個線程(通過其get或set方法)的線程都有其自己的,獨立初始化的變量副本。ThreadLocal實例通常是希望將狀態與線程關聯的類中的私有靜態字段(例如,用戶ID或事務ID)。

這意味著說2個線程t1t2執行someBMethod(),它們分別結束設置x1x2(的實例X)。現在,當t1come并執行時,someCMethod()它會獲取x1(它是由它自己設置的)和gets?。t2x2

換句話說,只有一個靜態實例是安全的ThreadLocal,因為在內部調用時它會執行類似的操作set

?

?

Java?源代碼

  1. java.lang.Thread Class包含一個實例變量,如下所示。

    ThreadLocal.ThreadLocalMap threadLocals = null;

因為threadLocals變量是非靜態的,所以應用程序中的每個線程(即Thread Class的每個實例)將擁有它自己的threadLocals映射副本

  1. 該映射的當前?ThreadLocal實例,而value是您作為參數傳遞給ThreadLocal.set()的值。

  2. 當您嘗試在內部獲取?as值時ThreadLocal.get(),它將從Current Thread的ThreadLocalMap獲取。

簡而言之,您是從當前線程對象獲取&設置值,而不是ThreadLocal對象獲取&設置值。

?

總結

以上是生活随笔為你收集整理的为什么jdk源码推荐ThreadLocal使用static的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。