新聞中心
這篇文章主要介紹“多線程ThreadLocal的作用是什么”,在日常操作中,相信很多人在多線程ThreadLocal的作用是什么問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”多線程ThreadLocal的作用是什么”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)建站!專注于網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、小程序開發(fā)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了吉利免費(fèi)建站歡迎大家使用!
一、ThreadLocal作用是什么?
ThreadLocal是針對共享變量而言的,如果多個(gè)線程都可能使用到這個(gè)某個(gè)變量,而這個(gè)變量又希望是線程自己管理,變動(dòng)無需其它線程知道,即變動(dòng)結(jié)果對自己產(chǎn)生作用即可,就可以將變量指定為ThreadLocal。
說白了:ThreadLocal即各個(gè)線程從主內(nèi)存區(qū)域?qū)⒆兞糠謩e克隆了一份,然后各自使用互不干擾。
二、代碼案例展示
package test.thread.threadlocal; public class ThreadLocalTest { ThreadLocallongLocal = new ThreadLocal (); ThreadLocal stringLocal = new ThreadLocal (); public void set() { longLocal.set(Thread.currentThread().getId()); stringLocal.set(Thread.currentThread().getName()); } public long getLong() { return longLocal.get(); } public String getString() { return stringLocal.get(); } public static void main(String[] args) throws InterruptedException { final ThreadLocalTest test = new ThreadLocalTest(); test.set(); System.out.println(test.getLong()); System.out.println(test.getString()); Thread thread1 = new Thread(){ public void run() { test.set(); System.out.println(test.getLong()); System.out.println(test.getString()); }; }; thread1.start(); thread1.join(); System.out.println(test.getLong()); System.out.println(test.getString()); } }
打印結(jié)果:
1 main 10 Thread-0 1 main
從代碼執(zhí)行結(jié)果來看,thread1對longLocal 和 stringLocal的改動(dòng),絲毫不影響主線程的值。
到此,關(guān)于“多線程ThreadLocal的作用是什么”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請繼續(xù)關(guān)注創(chuàng)新互聯(lián)網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
分享名稱:多線程ThreadLocal的作用是什么
文章出自:http://www.ef60e0e.cn/article/gsiiji.html