Threadlocalを使用して、クラスメンバー変数の安全でないスレッドの問題を解決する

@controler
public class UserHandler extends BaseControler{
    
    

	//这种方式引用全局变量Person,将会导致某一个线程对person进行修改时,其他线程获取person时会获取上一个线程修改后的person对象
	Person person=new Person();
	
	//解决方案,使用threadlocal
	private static ThreadLocal<Person> threadLocal=new ThreadLocal<Person>();
	//在需要使用person对象时,调用getPerson()方法来获取
	public static Person getPerson(){
    
    
		if (threadLocal.get() == null) {
    
    
			Person conn = new Person();
			threadLocal.set(conn);
			return conn;
		}else{
    
    
			return threadLocal.get();
		}
	}
}

おすすめ

転載: blog.csdn.net/qq_41454044/article/details/110918991