`
raymond.chen
  • 浏览: 1419726 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

ThreadLocal的使用范例

    博客分类:
  • Java
 
阅读更多

ThreadLocal用于保存某个线程的共享变量。

ThreadLocal在每个线程中对该变量会创建一个副本,即每个线程内部都会有一个该变量,且在线程内部任何地方都可以使用,线程之间互不影响。

 

值的存取过程:  ThreadLocal --> Current Thread --> ThreadLocalMap<ThreadLocal, Value> --> ThreadLocalMap.Entry<ThreadLocal, Value>

 

防止ThreadLocal的弱引用问题(会出现内存泄露):

       使用完线程共享变量后,显示调用remove方法清除线程共享变量

       将ThreadLocal定义为private static

 

public class ThreadLocalTest {
	private static ThreadLocal<String> threadLocal = new ThreadLocal<String>();
	
	public static void main(String[] args) throws Exception {
		threadLocal.set(Thread.currentThread().getName());
		
		Thread thread = new Thread(){
			public void run() {
				threadLocal.set(Thread.currentThread().getName());
				System.out.println(threadLocal.get());
				threadLocal.remove();
			};
		};
		thread.start();
		
		//join:等待thread执行完毕后,才能继续往下执行。join存在很大的性能问题,建议用CountDownLatch、CyclicBarrier等类替代join
		thread.join();

		System.out.println(threadLocal.get());
		threadLocal.remove();
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics