ThreadLocal对象通常用于防止对可变的单实例变量或全局变量进行共享。
package com.lxc.tet; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class MyThreadLocal<T> { private Map<Thread,T> map = new ConcurrentHashMap<Thread, T>(); protected T initialValue(){ return null; } public void set(T value){ map.put(Thread.currentThread(), value); } public T get(){ T result = null; result = map.get(Thread.currentThread()); if(result==null && !map.containsKey(Thread.currentThread())){ result=initialValue(); set(result); } return result; } public void remove(){ map.remove(Thread.currentThread()); } }
原文地址:https://www.cnblogs.com/lxcmyf/p/8390655.html
时间: 2024-10-10 10:36:42