引用jdk说明:
/**
* This class provides thread-local variables. These variables differ from
* their normal counterparts in that each thread that accesses one (via its
* <tt>get</tt> or <tt>set</tt> method) has its own, independently initialized
* copy of the variable. <tt>ThreadLocal</tt> instances are typically private
* static fields in classes that wish to associate state with a thread (e.g.,
* a user ID or Transaction ID).
**/
翻译:这个类提供了线程内局部变量。这些变量不同于一般的副本,每个线程都有自己的访问,依赖于初始化的变量拷贝。ThreadLocal实例通常声明为private static类型来和线程的状态通信。
下面几句话帮助了解ThreadLocal:
ThreadLocal主要是提供了保持对象的方法和避免参数传递的方便的对象访问方式。
在多线程并发中,ThreadLocal通过隔离线程存储数据,解决了多线程变量访问的冲突问题。
锁机制和ThreadLocal线程局部变量的本质区别在于是否共享变量(前者是,后者否),在这个大前提之下,锁机制是时间换空间(防止并发的本质,即串行化),ThreadLocal是空间换时间(变量差异化,互不干涉,也是需求所致)【后半句这样说没太多意义,主要是帮助理解,脱离误区!】。
先看个简单的demo:
package com.caiya.test._concurrent;
/**
* Created by caiya on 16/4/5.
*/
public class TestNum {
// 匿名内部类定义ThreadLocal的子类,并重写部分方法
private static ThreadLocal<Integer> seqNum = new ThreadLocal<Integer>(){
@Override
protected Integer initialValue() {
return 0;
}
};
public int getNextNum(){
seqNum.set(seqNum.get() + 1);
return seqNum.get();
}
public static void main(String[] args) {
TestNum test = new TestNum();
// 启动三个线程,并共享同一个实例
ThreadClient t1 = new ThreadClient(test);
ThreadClient t2 = new ThreadClient(test);
ThreadClient t3 = new ThreadClient(test);
t1.start();
t2.start();
t3.start();
}
// 线程客户端
private static class ThreadClient extends Thread{
private TestNum test;
public ThreadClient(TestNum test){
this.test = test;
}
@Override
public void run() {
for (int i = 0; i<3; i++){
System.out.println(Thread.currentThread().getName() + "thread[" + i + "]:" + " --> sn.nextNum:" + test.getNextNum());
}
}
}
}
执行结果:
Thread-2thread[0]: --> sn.nextNum:1
Thread-2thread[1]: --> sn.nextNum:2
Thread-0thread[0]: --> sn.nextNum:1
Thread-2thread[2]: --> sn.nextNum:3
Thread-1thread[0]: --> sn.nextNum:1
Thread-1thread[1]: --> sn.nextNum:2
Thread-0thread[1]: --> sn.nextNum:2
Thread-0thread[2]: --> sn.nextNum:3
Thread-1thread[2]: --> sn.nextNum:3
可以看到各个线程内部变量互不干扰。