Java多執行緒 ThreadLoacl

2021-09-09 06:36:33 字數 1404 閱讀 1629

先看下測試的**

public class testthreadlocal  catch (interruptedexception e) 

creatthread().start();

creatthread().start();

try catch (interruptedexception e)

system.out.println("子執行緒啟動後:"+thread.currentthread().getname()+"_"+shareval.get());

}public static thread creatthread() catch (interruptedexception e)

system.out.println(thread.currentthread().getname()+" get_"+shareval.get());

}});

}}結果如下:

我們在threadloacl型別變數shareval初始化時,重寫 initialvalue 給初始值,如下:

public class testthreadlocal 

};public static void main(string args) catch (interruptedexception e)

creatthread().start();

creatthread().start();

try catch (interruptedexception e)

system.out.println("子執行緒啟動後:"+thread.currentthread().getname()+"_"+shareval.get());

}public static thread creatthread() catch (interruptedexception e)

system.out.println(thread.currentthread().getname()+" get_"+shareval.get());

}});

}}結果如下:

對比可以可以得到,threadlocal類,每個執行緒都會複製乙個副本到執行緒本地中,即從程序的堆中將threadloacl 的值複製到每個執行緒的棧中。然後執行緒修改只會修改本地的值,而不會互相影響產生髒讀等錯誤。

每個執行緒thread 類中都有 乙個threadlocal.threadlocals成員變數threadlocalmap,這個是map,key為執行緒自己this,value為 傳入的實際值。

有趣可以看下原始碼。

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...