ThreadLocal
1.线程局部变量,是一种多线程并发访问变量的解决方案,与同步技术 synchronize 加锁的方式不同,threadlocal完全不提供锁,而使用
空间换时间的手段,为每个线程提供变量的独立副本,一保证现成的安全。
2.在并发不是很高的时候,加锁的性能会更好,但是作为一套完全无关的线程安全解决方案,减少锁的竞争。
package demo3;
import java.util.concurrent.TimeUnit;
/**
* Created by liudan on 2017/7/7.
*/
public class MyThread1 {
public static ThreadLocal<String> threadLocalString = new ThreadLocal<String>();
public void setThreadLocalString(String string) {
threadLocalString.set(string);
}
public void getThreadLocalString() {
System.err.println("◆:" + Thread.currentThread().getName() + ":" + threadLocalString.get());
}
public static void main(String[] args) {
final MyThread1 myThread1 = new MyThread1();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
myThread1.setThreadLocalString("张帅");
myThread1.getThreadLocalString();
}
},"T0000-01");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
TimeUnit.SECONDS.sleep(0);
myThread1.setThreadLocalString("张帅1111");
myThread1.getThreadLocalString();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"T0000-02");
t1.start();
t2.start();
}
}
输出:
◆:T0000-01:张帅 ◆:T0000-02:张帅1111