java并发编程--ThreadLocal 概念

package cn.bufanli.test;

/**
 * ThreadLocal 概念: 线程局部变量,使用一种多线程间并发访问变量的解决方案.
 * 与其synchronized等加锁的方式不同,ThreadLocal 完全不提供锁,而使用空间换时间的
 * 手段,为每个线程提供变量的独立副本,以保障线程安全
 * 从性能上说,ThreadLocal不具备绝对的优势,在并发不是很高的时候,加锁的性能会更好,但作为一套与锁
 * 完全无关的线程安全解决方案,在高并发量或者竞争激烈的场景,使用ThreadLocal可以在一定程度上减少锁竞争.
 */
public class ThreadLocalDemo {
    private static ThreadLocal<String> th = new ThreadLocal<>();
    public void getTh(){
        System.out.println(Thread.currentThread().getName() + ":" + th.get());
    }
    public void setTh(String value){
        th.set(value);
    }

    public static void main(String[] args) {
        final ThreadLocalDemo ct = new ThreadLocalDemo();
        new Thread(()->{
            ct.setTh("张三");
            ct.getTh();
        }).start();
        new Thread(()->{
           try {
               Thread.sleep(100);
               ct.getTh();
           }catch(Exception e){
               e.printStackTrace();
           }
        }).start();
    }
}

猜你喜欢

转载自blog.csdn.net/adminBfl/article/details/103231654