java.lang.ThreadLocal可以用来存放线程的局部变量,每个线程都有单独的局部变量,彼此之间不会共享。ThreadLocal<T>类主要包含3个方法:
- public T get():返回当前线程的局部变量。
- protected T initialValue():返回当前线程局部变量的初始值。
- public void set(T value):设置当前线程的局部变量。
ThreadLocal是如何做到为每个线程提供单独的局部变量的?
原因很简单,在ThreadLocal类中有一个Map缓存,用来存储每个线程的局部变量。
ThreadLocal具体用法
public class Count {
private static int count;
private static ThreadLocal<Integer> serialCount = new ThreadLocal<Integer>() {
protected synchronized Integer initialValue() {
return new Integer(count++);
}
};
public static int get() {
return serialCount.get();
}
public static void set(int i) {
serialCount.set(i);
}
}
public class ThreadLocalTest extends Thread {
public void run() {
for(int i = 0;i < 3;i++) {
int c = Count.get();
System.out.println(getName() + ": " + c);
Count.set(c+=2);
}
}
public static void main(String[] args) {
ThreadLocalTest t = new ThreadLocalTest();
ThreadLocalTest t2 = new ThreadLocalTest();
t.start();
t2.start();
}
}
520

被折叠的 条评论
为什么被折叠?



