ThreadLocal小技巧

1.ThreadLocal是每个线程存放共享变量区域,一般没有存值的情况下get总是返回null。以下是初始化 ThreadLocal的默认值:
public static void main(String[] args) throws InterruptedException {
	ThreadLocal<String> threadLocal = new ThreadLocal<String>(){
		@Override
		protected String initialValue() {
			return "设置默认值";
		}
	};
	
	System.out.println(threadLocal.get());
}
结果:

设置默认值

2.ThreadLocal是隔离每个线程的。但如果想要在子线程中取得主线程中的值,就要使InheritableThreadLocal。如:

private static InheritableThreadLocal<String> shareLocal = new InheritableThreadLocal<String>();
public static void main(String[] args) throws InterruptedException {
	shareLocal.set("main set : hello");
	
	new Thread(){
		public void run() {
			System.out.println(shareLocal.get());
		};
	}.start();
}

结果:
main set : hello


你可能感兴趣的:(ThreadLocal小技巧)