ThreadLocal的使用

本文介绍了一个实用的ThreadLocal工具类实现,该工具类能够帮助开发者更好地管理线程局部变量,确保不同线程间的变量隔离。文章通过示例展示了如何使用这个工具类来存储和检索线程局部变量。

定义一个ThreadLocal工具类。

package com.java;
import java.util.HashMap;
import java.util.Map;


public class UtilsThreadContext {

    private static final ThreadLocal<Map<Object, Object>> currentThreadCache = new ThreadLocal<>();
    public static Map<Object, Object> get() {


        return currentThreadCache.get();
    }

    public static <T> T get(Object fqn) {
        Map<Object, Object> map = currentThreadCache.get();
        if (map == null) {
            return null;
        }
        return (T) map.get(fqn);

    }

    public static boolean containsKey(Object fqn) {
        Map<Object, Object> map = currentThreadCache.get();
        if (map == null) {
            return false;
        }
        return map.containsKey(fqn);

    }

    public static void put(Object fqn, Object value) {

        if (fqn != null) {
            Map<Object, Object> map = currentThreadCache.get();
            if (map == null) {
                map = new HashMap<Object, Object>();
                currentThreadCache.set(map);
            }
            map.put(fqn, value);
        }
    }

    public static void putAll(Map<?, ?> m) {

        if (m != null) {
            Map<Object, Object> map = currentThreadCache.get();
            if (map == null) {
                map = new HashMap<Object, Object>();
                currentThreadCache.set(map);
            }
            map.putAll(m);
        }
    }

    public static void delete(Object fqn) {
        if (fqn != null) {
            Map<Object, Object> map = currentThreadCache.get();
            if (map != null) {
                map.remove(fqn);
            }
        }
    }

    public static void cleanup() {
        try {
            currentThreadCache.remove();
        } catch (Throwable e) {
        }
    }
}


测试:

public class test {
    public static void main(String[] args) {

        IntStream.range(0, 10).forEach(i -> {
            new Thread(() -> {

                String msg = "消息"+i;
                UtilsThreadContext.put(i, msg);
                System.out.println(Thread.currentThread().getName() + ":" + "放入消息是"+msg);
                System.out.println(Thread.currentThread().getName() + ":" + "取出消息是"+UtilsThreadContext.get(i));

            }).start();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}

测试结果:

每个线程获取的变量都是当前线程的。互不影响。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值