java ThreadLocal 使用

ThreadLocal
    线程内 threadLocal.set(), 只是当前线程能 threadLocal.get() 到
    只能设置一个对象,可set map对象。
    容易造成内存泄漏,每次使用完ThreadLocal,都调用它的remove()方法,清除数据

/**
 * ThreadLocal的set的变量只是当前线程可看
 * ThreadLocal set的变量只有一个,经常set Map
 */
public class ThreadLocalTest {

    static ThreadLocal threadLocal = new ThreadLocal();

    public static void main(String[] args) {

        new Thread(()->{
            System.out.println("线程1");
            Map<String,String> dataMap = new HashMap<>();
            threadLocal.set(dataMap);//往当前线程里面设置个对象 map,其它线程得不到这个数据
            System.out.println("线程1 往线程变量中 加入数据 ");
            dataMap.put("name","thread1");
            Map<String,String> getMap = (Map<String, String>) threadLocal.get();//从当前线程把对象拿出
            System.out.println("线程1 get:"+getMap.get("name"));
        }).start();

        new Thread(()->{
            try {
                System.out.println("线程2 等待1秒 让线程1 先执行完");
                Thread.sleep(1000);
                System.out.println("线程2 是否能拿取线程1 线程变量是否为空 结果:"+ (threadLocal.get() == null));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

执行结果:

线程1
线程1 往线程变量中 加入数据 
线程1 get:thread1
线程2 等待1秒 让线程1 先执行完
线程2 是否能拿取线程1 线程变量是否为空 结果:true

发布了60 篇原创文章 · 获赞 6 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/xiaoluo5238/article/details/104360178