最近在看Spring的时候回顾了一下ThreadLocal,下面是ThreadLocal的使用说明。
package org.lmu.threadlocal; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class ThreadLocal<T> { private Map<Thread,T> map = Collections.synchronizedMap(new HashMap<Thread, T>()); /** * 取得线程局部变量的值 * @return 线程局部变量的值 */ public T get(){ Thread currenThread = Thread.currentThread(); T temp = map.get(currenThread);//取得线程局部变量的值 if(temp==null&&map.containsKey(currenThread)){ temp = initialValue(); map.put(currenThread, temp); } return temp; } /** * 设置当前线程局部变量的值 * @param value 局部变量需设的值 */ public void set(T value){ map.put(Thread.currentThread(), value); } /** * 将线程局部变量的值删除 */ public void remove(){ map.remove(Thread.currentThread()); } /** * 线程局部变量初始值 * @return 初始值为null */ public T initialValue(){ return null; } }
package org.lmu.threadlocal; public class ThreadLocalTest { //通过覆写ThreadLocal中的initialValue方法为线程局部变量初始化之为0 ThreadLocal<Integer> tlNum = new ThreadLocal<Integer>(){ protected Integer initialValue() { return 0; } }; /** * * @return 下一个值 */ public int getNextNum(){ Integer num = tlNum.get();//取得下一个值 tlNum.set(num+1);//设置下一个值 return num;//返回取得的值 } private static class TestThread implements Runnable{ private ThreadLocalTest tlt; public TestThread(ThreadLocalTest tlt) { this.tlt = tlt; } public void run() { int n = 3; for (int i = 0; i < n; i++) { System.out.println("线程【"+Thread.currentThread().getName()+"】-线程变量值【"+tlt.getNextNum()+"】"); } } } public static void main(String[] args) { //TestThread tt1 = new TestThread(new ThreadLocalTest()); //TestThread tt2 = new TestThread(new ThreadLocalTest()); //TestThread tt3 = new TestThread(new ThreadLocalTest()); //之前这样写是不正确的 ThreadLocalTest tlt = new ThreadLocalTest(); TestThread tt1 = new TestThread(tlt); TestThread tt2 = new TestThread(tlt); TestThread tt3 = new TestThread(tlt); Thread t1 = new Thread(tt1); Thread t2 = new Thread(tt2); Thread t3 = new Thread(tt3); t1.start(); t2.start(); t3.start(); } }