ThreadLocal为解决多线程程序的并发问题提供了一种新的思路。使用这个工具类可以很简洁地编写出优美的多线程程序,ThreadLocal并不是一个Thread,而是Thread的局部变量。
先上一个小demo:
public class ThreadLocalDemo { public static ThreadLocal<Integer> integerThreadLocal = new ThreadLocal<>(); public static void main(String[] args) { Thread thread1 = new Thread(new ThreadTest()); Thread thread2 = new Thread(new ThreadTest()); Thread thread3 = new Thread(new ThreadTest()); thread1.start(); thread2.start(); thread3.start(); } static class ThreadTest implements Runnable { private int count = 0; @Override public void run() { for (int i = 0; i < 3; i++) { count ++; integerThreadLocal.set(count); System.out.println("线程名:" + Thread.currentThread().getName() + ";值是:" + integerThreadLocal.get()); } } } }
运行结果
线程名:Thread-1;值是:1
线程名:Thread-2;值是:1
线程名:Thread-0;值是:1
线程名:Thread-0;值是:2
线程名:Thread-0;值是:3
线程名:Thread-2;值是:2
线程名:Thread-1;值是:2
线程名:Thread-2;值是:3
线程名:Thread-1;值是:3
发现静态的Threadlocal里面保存的变量并没有因为多线程的修改而覆盖,实际上是依存于当前线程;废话不多说看看Threadlocal的关键方法:
public void set(T value) { Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) map.set(this, value); else createMap(t, value); }
void createMap(Thread t, T firstValue) { t.threadLocals = new ThreadLocalMap(this, firstValue); }
ThreadLocalMap(ThreadLocal<?> firstKey, Object firstValue) { table = new Entry[INITIAL_CAPACITY]; int i = firstKey.threadLocalHashCode & (INITIAL_CAPACITY - 1); table[i] = new Entry(firstKey, firstValue); size = 1; setThreshold(INITIAL_CAPACITY); }我们可以看到 存储值用的是ThreadLocalMap,在第一次创建的时候是把线程作为key,要保存的变量值做value保存进去的,ThreadLocal用于保存某个线程共享变量:对于同一个static ThreadLocal,不同线程只能从中get,set,remove自己的变量,而不会影响其他线程的变量。