一、概念
線程局部變量,是一種多線程併發訪問變量的解決方案。與synchronized等加鎖的方式不同,ThreadLocal完全不提供鎖。而使用以空間換時間的手段,爲每個線程提供變量的副本,以保證線程安全。
從性能上來說,ThreadLocal不具有絕對的優勢,在併發不是很高的時候,加鎖的性能會更好,但是作爲一套與鎖完全無關的線程安全解決方案,在高併發量或者競爭激烈的場景,使用ThreadLocal可以在一定程度上減少鎖競爭。
public class ConnThreadLocal {
public static ThreadLocal<String> th = new ThreadLocal<String>();
public void setTh(String value){
th.set(value);
}
public void getTh(){
System.out.println(Thread.currentThread().getName() + ":" + this.th.get());
}
public static void main(String[] args) throws InterruptedException {
final ConnThreadLocal ct = new ConnThreadLocal();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
ct.setTh("張三");
ct.getTh();
}
}, "t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
ct.setTh("李四");
ct.getTh();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t2");
t1.start();
t2.start();
}
}