ThreadLocal用法初探

ThreadLocal主要用来提供线程局部变量,也就是变量只对当前线程可见。

code:

package Test;

import java.util.HashMap;

class ThreadLocalMap extends HashMap<String, Object> {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static ThreadLocal<ThreadLocalMap> threadLocal = new ThreadLocal<ThreadLocalMap>();

	private ThreadLocalMap() {
	}

	public static ThreadLocalMap getThreadLocalMap() {
		ThreadLocalMap instance = threadLocal.get();
		if (instance == null) {
			instance = new ThreadLocalMap();
			threadLocal.set(instance);
		}
		return threadLocal.get();
	}

}

public class Test {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ThreadLocalMap m = ThreadLocalMap.getThreadLocalMap();
		m.put("1", "wwx");
		String str = ThreadLocalMap.getThreadLocalMap().get("1").toString();
		System.err.println(str);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_32771571/article/details/79723886