java 线程 ThreadLocal 线程局部变量

  • 以空间换时间,为每个线程提供独立的变量副本,以保证线程安全
  • 作为一套完全与锁无关的线程安全解决方案,在高并发或者竞争激烈的情况下,ThreadLocal在一定程度上减少锁竞争
  • 从性能上说,ThreadLocal并不具备绝对优势,在并发不高的情况下,加锁的性能会更好
public class ConnThreadLocal {

    public static ThreadLocal th = new ThreadLocal();
    
    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.getTh();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t2");
        
        t1.start();
        t2.start();
    }
    
}

你可能感兴趣的:(java 线程 ThreadLocal 线程局部变量)