---
title: "Java threadLocal类 笔记"
author: "boyuliu"
date: "2015-03-17T17:36:11Z"
tags: []
categories: ["编程语言"]
slug: "java-threadlocal"
draft: false
lastmod: "2015-03-17T17:36:11Z"
id: 2193289
url: "https://boyuliu.iteye.com/blog/2193289"
---

ThreadLocal 类是JDK .lang包下的一个类，该类提供了线程局部 (thread-local) 变量。这些变量不同于它们的普通对应物，因为访问某个变量（通过其 `get` 或 `set` 方法）的每个线程都有自己的局部变量，它独立于变量的初始化副本。`ThreadLocal` 实例通常是类中的 private static 字段，它们希望将状态与某一个线程（例如，用户 ID 或事务 ID）相关联。  
简单来说，比如说一个非线程安全的对象HashMap。并且碰巧你并不需要在不同的线程中共享这个属性，也就是说这个属性不存在 跨线程的意义。那么你不要sychronize这么复杂的东西，ThreadLocal不错。

 

ThreadLocal类存在一个内部类ThreadLocalMap,该map用于维护每个线程所对应的参数，它以Thread.currentThread()为key，来存储当前线程所有需要的变量参数;

```
    /**
     * Sets the current thread's copy of this thread-local variable
     * to the specified value.  Most subclasses will have no need to 
     * override this method, relying solely on the {@link #initialValue}
     * method to set the values of thread-locals.
     *
     * @param value the value to be stored in the current thread's copy of
     *        this thread-local.
     */
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }
```

 

看一个简单的demo：起3个线程，都去调用一个公共的ThreadLocal中的HashMap，并打印。

```
package demo;

import java.util.HashMap;

public class ThreadLocalTest {

	public static ThreadLocal map0 = new ThreadLocal() {

		@Override
		protected HashMap initialValue() {
			System.out
					.println(Thread.currentThread().getName()
							+ " ThreadLocalTest - initialValue() - do initial with hashMap");
			return new HashMap();
		}
	};

	public void run() {
		Thread[] runItem = new Thread[3];

		for (int i = 0; i < runItem.length; i++) {
			runItem[i] = new Thread(new T1(i));
		}

		for (int i = 0; i < runItem.length; i++) {
			runItem[i].start();
		}
	}

	class T1 implements Runnable {

		int id;

		public T1(int id) {
			this.id = id;
		}

		@Override
		public void run() {
			System.out.println(Thread.currentThread().getName()
					+ " T1 - run() - start to work");
			HashMap map = map0.get();
			for (int i = 0; i < 10; i++) {
				map.put(i, i + id * 100);
				try {
					Thread.sleep(100);
				} catch (Exception ex) {
				}
			}
			System.out.println(Thread.currentThread().getName()
					+ " T1 - run() - println hashMap >> " + map);
		}

	}

	public static void main(String[] args) {
		ThreadLocalTest threadts = new ThreadLocalTest();
		threadts.run();
	}
}
```

 

\------------------------------------------------------------------------------------  
输出结果如下：  
Thread-0 T1 - run() - start to work  
Thread-0 ThreadLocalTest - initialValue() - do initial with hashMap  
Thread-2 T1 - run() - start to work  
Thread-2 ThreadLocalTest - initialValue() - do initial with hashMap  
Thread-1 T1 - run() - start to work  
Thread-1 ThreadLocalTest - initialValue() - do initial with hashMap  
Thread-0 T1 - run() - println hashMap &gt;&gt; {0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9}  
Thread-1 T1 - run() - println hashMap &gt;&gt; {0=100, 1=101, 2=102, 3=103, 4=104, 5=105, 6=106, 7=107, 8=108, 9=109}  
Thread-2 T1 - run() - println hashMap &gt;&gt; {0=200, 1=201, 2=202, 3=203, 4=204, 5=205, 6=206, 7=207, 8=208, 9=209}

很明显可以看出，虽然Thread-0、Thread-1、Thread-2 都是共享一个ThreadLocal，但是每个线程都在操作自己的HashMap.