public class ThreadLocalDemo {
public static class MyRunnable implements Runnable {
// The ThreadLocal class in Java enables you to create variables that
// can only be read and written by the same thread. Thus, even if two
// threads are executing the same code, and the code has a reference to
// a ThreadLocal variable, then the two threads cannot see each other's
// ThreadLocal variables.
private ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
// you can specify an initial value for a ThreadLocal object by
// subclassing ThreadLocal and overriding the initialValue() method.
@Override
protected Integer initialValue() {
return 123456789; // It is visible to all threads.
}
};
@Override
public void run() {
String threadName = Thread.currentThread().getName();
// All threads will see the same initial value when calling get()
// before having called set().
System.out.println(threadName + ", init: " + threadLocal.get());
threadLocal.set((int) (Math.random() * 100D));
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
// If two different threads set different values on the same
// ThreadLocal object, they cannot see each other's values.
System.out.println(threadName + ", random: " + threadLocal.get());
}
}
public static void main(String[] args) {
MyRunnable sharedRunnableInstance = new MyRunnable();
Thread thread1 = new Thread(sharedRunnableInstance);
Thread thread2 = new Thread(sharedRunnableInstance);
thread1.start();
thread2.start();
/* Console:
Thread-0, init: 123456789
Thread-1, init: 123456789
Thread-1, random: 82
Thread-0, random: 95
*/
}
}
ThreadLocal例子
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
- 文/潘曉璐 我一進店門脑融,熙熙樓的掌柜王于貴愁眉苦臉地迎上來缩宜,“玉大人甥温,你說我怎么就攤上這事∫鲵荆” “怎么了?”我有些...
- 文/不壞的土叔 我叫張陵狰挡,是天一觀的道長肛著。 經(jīng)常有香客問我,道長枢贿,這世上最難降的妖魔是什么? 我笑而不...
- 正文 為了忘掉前任超凳,我火速辦了婚禮,結(jié)果婚禮上轮傍,老公的妹妹穿的比我還像新娘首装。我一直安慰自己创夜,他們只是感情好仙逻,可當我...
- 文/花漫 我一把揭開白布系奉。 她就那樣靜靜地躺著檬贰,像睡著了一般缺亮。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上萌踱,一...
- 文/蒼蘭香墨 我猛地睜開眼织鲸,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了搂擦?” 一聲冷哼從身側(cè)響起哗脖,我...
- 正文 年R本政府宣布远寸,位于F島的核電站屠凶,受9級特大地震影響驰后,放射性物質(zhì)發(fā)生泄漏矗愧。R本人自食惡果不足惜,卻給世界環(huán)境...
- 文/蒙蒙 一夜涕、第九天 我趴在偏房一處隱蔽的房頂上張望属愤。 院中可真熱鬧女器,春花似錦春塌、人聲如沸。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽锅必。三九已至,卻和暖如春惕艳,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背远搪。 一陣腳步聲響...
推薦閱讀更多精彩內(nèi)容
- 伊萬卡隊___王利雄A1 訓(xùn)練營第一周R4 ...
- MD5作為文件校驗方法已經(jīng)不可靠了,可以人為制造碰撞郎逃。 JPEG圖片樣本 簡書會對上傳的圖片進行壓縮,參考鏈接(需...