Java多執行緒 ThreadLocal

2021-09-19 07:49:35 字數 1042 閱讀 2305

threadlocal 是jdk 包提供的,它提供了執行緒本地變數,也就是如果你建立了乙個threadlocal 變數,那麼訪問這個變數的每個執行緒都會有這個變數的乙個本地副本。當多個執行緒操作這個變數時,實際操作的是自己本地記憶體裡面的變數,從而避免了執行緒安全問題。建立乙個threadlocal 變數後,每個執行緒都會複製乙個變數到自己的本地記憶體。

public

void

set(t value)

void

createmap

(thread t, t firstvalue)

theadlocal操控是是兩個位於thread中的變數,且初始值為null

threadlocal.threadlocalmap threadlocals = null;

threadlocal.threadlocalmap inheritablethreadlocals = null;

這個兩個變數型別為threadlocalmap位於是threadlocal的內部類

static

class

threadlocalmap..

.}

而threadlocalmap是乙個定製化的hashmap。

其key是threadlocal,value是object

再看get方法

public t get()

}return

setinitialvalue()

;}

threadlocalmap getmap

(thread t)

大致關係是這樣

java多執行緒

在網上看到很有意思的問題,摘下來好好看下 在面試的時候被問了乙個多執行緒的問題 回來仔細思考了一下,多執行緒是否真的能提高了效率?我對多執行緒的理解就是 比如挖乙個隧道,有2種開工方法 1 只在山的一頭挖,直至挖到山的另一頭,從而打通隧道,這可以看成是單執行緒 2 在山的兩頭挖,同時開工,最後在山的...

Java 多執行緒

1。thread類和runnable介面 2。主線程 用thread的static thread currentthread 方法獲得 3。通過實現runnable介面建立執行緒 實現runnable介面的run方法。新執行緒在run 方法返回時結束。注意用這種方法建立程序時,在實現runnable...

JAVA 多執行緒

為hashmap的不正確使用所導致。hashmap在多執行緒環境下使用不安全。使用靜態hashmap作為聯絡人資料快取,key為手機號碼.private static maplxrdata new hashmap 多執行緒環境下不同步hashmap可能導致如下問題 1 多執行緒put操作後可能導致g...