通过ThreadLocal实现每个线程拥有自己独立Session


编写原因:当使用ThreadLocal维护变量时,ThreadLocal为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本,防止了Session共用。

demo1:SessionUtil作用

private static SessionFactory  factory;
private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();
//获取sessionFactory加载配置信息,放置于静态代码块为保证代码的优先执行
static {
//读取配置文件
Configuration cfg=new Configuration().configure();
//创建SessionFactory
factory=cfg.buildSessionFactory();
}

public static Session getSession(){
//获取session
Session session=threadLocal.get();
if(session==null){
System.out.println("session is  null");
session=factory.openSession();
threadLocal.set(session);
}
return session;
}

public static void closeSession(){
Session session=threadLocal.get();
//如果Session不为空,关闭session并清空session
if(session!=null){
session.close();
threadLocal.set(null);

}


开始测试:

2.创建localThread继承Thread

import org.hibernate.Session;

public class localThread extends Thread {
public void run(){
Session s1=demo1.getSession();
Session s2=demo1.getSession();
Session s3=demo1.getSession();
//获取线程id,线程Id为long类型
long threadId=this.getId();
System.out.println("线程"+threadId+":\n"
+ s1.hashCode() + "\n" 
             + s2.hashCode() + "\n"
             +s3.hashCode());

}

}

3.Test类

public class testThread  {
public static void main(String[] args) {
localThread thread1 = new localThread();
localThread thread2 = new localThread();
localThread thread3 = new localThread();
        //启动线程
thread1.start();
thread2.start();
thread3.start();
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值