2019独角兽企业重金招聘Python工程师标准>>>
ThreadLocal 本地线程,容器用来存放线程的局部变量
例子对比
public interface Sequence {
int getNumber();
}
public class ClientThread extends Thread {
private Sequence sequence;
public ClientThread(Sequence sequence) {
this.sequence = sequence;
}
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName() + "=>" + sequence.getNumber());
}
}
}
public class SequenceA implements Sequence {
//线程之间共享的static变量无法保证对于不同线程是安全的
private static int number = 0;
public int getNumber() {
number = number + 1;
return number;
}
public static void main(String[] args) {
Sequence sequence = new SequenceA();
ClientThread thread1 = new ClientThread(sequence);
ClientThread thread2 = new ClientThread(sequence);
ClientThread thread3 = new ClientThread(sequence);
thread1.start();
thread2.start();
thread3.start();
}
}
public class SequenceB implements Sequence {
// 同样是static变量,没有被共享,而是每个线程各一份,ThreadLocal为每一个线程提供了一个独立的副本。
private static ThreadLocal
protected Integer initialValue() {
return 0;
}
};
public int getNumber() {
numberContainer.set(numberContainer.get() + 1);
return numberContainer.get();
}
public static void main(String[] args) {
Sequence sequence = new SequenceB();
ClientThread thread1 = new ClientThread(sequence);
ClientThread thread2 = new ClientThread(sequence);
ClientThread thread3 = new ClientThread(sequence);
thread1.start();
thread2.start();
thread3.start();
}
}
ThreadLocal的api
public void set(T value);//将值放入线程局部变量
public T get();
public void remove();
protected T initialValue();
实现自己的ThreadLocal
public class MyThreadLocal
private Map
public void set(T value) {
container.put(Thread.currentThread(), value);
}
public T get() {
Thread thread = Thread.currentThread();
T value = container.get(thread);
if (value == null && !container.containsKey(thread)) {
value = initialValue();
container.put(thread, value);
}
return value;
}
public void remove() {
container.remove(Thread.currentThread());
}
protected T initialValue() {
return null;
}
}