ThreadLocal这个类,理解起来比较简单,但是使用时,还是需要一些技巧的,简单介绍如下:
例子1:threadLocal变量一般用法
- package concurrent.thread;
- /**
- * 技巧:
- * 1.在当前线程里执行threadLocal.set(value) 相当于 currentThread.threadLocalMap.set(threadLocal,value)。
- * 即:每个线程均含有一个threadLocalMap变量,该变量由ThreadLocal维护。
- * 2.ThreadLocal变量一般使用private static修饰。
- */
- public class ThreadLocalDemo_step0 {
- private static ThreadLocal<String> myData = new ThreadLocal<String>();
- public static void main(String[] args) {
- Thread t1 = new Thread(new Runnable(){
- public void run() {
- System.out.println("Thread " + Thread.currentThread().getName() + "[begin] has " + myData.get());
- myData.set("t1");
- System.out.println("Thread " + Thread.currentThread().getName() + "[end] has " + myData.get());
- }
- });
- Thread t2 = new Thread(new Runnable(){
- public void run() {
- System.out.println("Thread " + Thread.currentThread().getName() + "[begin] has " + myData.get());
- myData.set("t2");
- System.out.println("Thread " + Thread.currentThread().getName() + "[end] has " + myData.get());
- }
- });
- t1.start();
- t2.start();
- }
- }
例子2:threadLocal变量的简单封装用法(重要)
- package concurrent.thread;
- /**
- * 技巧:
- * 3.如果希望线程局部变量初始化其它值,那么需要自己实现ThreadLocal的子类并重写initialValue()方法,
- * 通常使用一个内部匿名类对ThreadLocal进行子类化.比如下面的例子,SerialNum类为每一个类分配一个序号:
- */
- public class ThreadLocalDemo_step1 {
- public static void main(String[] args) {
- Thread t1 = new Thread(new Runnable(){
- public void run() {
- System.out.println("Thread " + Thread.currentThread().getName() + " has " + SerialNum.get());
- }
- });
- Thread t2 = new Thread(new Runnable(){
- public void run() {
- System.out.println("Thread " + Thread.currentThread().getName() + " has " + SerialNum.get());
- }
- });
- t1.start();
- t2.start();
- }
- //技巧:对threadLocal变量进行简单封装,可以简化多线程操作
- static class SerialNum {
- // The next serial number to be assigned
- private static int nextSerialNum = 0;
- private static ThreadLocal serialNum = new ThreadLocal() {
- protected synchronized Object initialValue() {
- return new Integer(nextSerialNum++);
- }
- };
- public static int get() {
- return ((Integer) (serialNum.get())).intValue();
- }
- }
- }
参考文献:
http://my.oschina.net/ITBoy/blog/17190 java类ThreadLocal的理解
http://www.iteye.com/topic/103804 正确理解ThreadLocal
原文http://suo.iteye.com/blog/1342393