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例子
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...