ThreadLocal其实特别简单:就是为每一个线程创建一个局部变量。
如果不用ThreadLocal的效果:
public class Order {
public int count = 0;
public Integer getNumber() {
return count++;
}
}
public class NewThread extends Thread {
private Order order;
public NewThread(Order order) {
this.order = order;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName() + " :" + order.getNumber());
}
}
}
public class Test {
public static void main(String[] args) {
Order order = new Order();
NewThread n1 = new NewThread(order);
NewThread n2 = new NewThread(order);
NewThread n3 = new NewThread(order);
n1.start();
n2.start();
n3.start();
/**
* 打印结果:
*
* Thread-2 :0
* Thread-0 :2
* Thread-1 :1
* Thread-0 :4
* Thread-2 :3
* Thread-0 :6
* Thread-1 :5
* Thread-2 :7
* Thread-1 :8
*
* 多个线程共享了这个变量
*/
}
}
如果使用ThreadLocal会是什么样呢 ?
public class Order {
public int count = 0;
/**
* 本地线程
*/
private static ThreadLocal<Integer> threadLocal = new ThreadLocal<Integer>() {
/**
* 赋值: 初始值
* @return
*/
@Override
protected Integer initialValue() {
return 0;
}
};
public Integer getNumber() {
count = threadLocal.get() + 1;
threadLocal.set(count);
return count;
}
}
public class NewThread extends Thread {
private Order order;
public NewThread(Order order) {
this.order = order;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName() + " :" + order.getNumber());
}
}
}
public class Test {
public static void main(String[] args) {
Order order = new Order();
NewThread n1 = new NewThread(order);
NewThread n2 = new NewThread(order);
NewThread n3 = new NewThread(order);
n1.start();
n2.start();
n3.start();
/**
* 打印结果:
*
* Thread-2 :1
* Thread-0 :1
* Thread-1 :1
* Thread-0 :2
* Thread-2 :2
* Thread-0 :3
* Thread-1 :2
* Thread-2 :3
* Thread-1 :3
*
* 每个线程,都将变量,标识为自己的局部变量
*/
}
}
所以ThreadLocal的源码:其实就是为每个线程都创建一个单独的变量。