每条线程都有属于自己的一个session实例

为什么使用TreadLocal?  
当使用ThreadLocal中维护变量时,ThreadLocal的为每个使用该变量的线程提供独立的变量副本,所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。  
具体实现如下:  

创建³³类  SessionUtil.java

[java] view plain copy
import org.hibernate.Session;  
import org.hibernate.SessionFactory;  
import org.hibernate.cfg.Configuration;  
  
public class SessionUtil {  
    private static SessionFactory factory;  
    private static ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();  
  
    // 静态初始化块,加载配置信息,获取SessionFactory  
    static {  
        // 读取hibernate.cfg.xml文件  
        Configuration cfg = new Configuration().configure();  
        // 建立SessionFactory  
        factory = cfg.buildSessionFactory();  
    }  
  
    public static Session getSession() {  
        //获取当前线程下的session  
        Session session = threadLocal.get();  
        //如果session为null,则从SessionFactory中获取一个session放入ThreadLocal  
        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不为null,则关闭session,并清空ThreadLocal  
        if(session!=null) {  
            session.close();  
            threadLocal.set(null);  
        }  
    }  
  
}  

接下来进行测试:  
首先创建³³ MyThread.java并继承线程

import org.hibernate.Session;

public class MyThread extends Thread{

    @Override
    public void run() {
        Session session1 = SessionUtil.getSession();
        Session session2 = SessionUtil.getSession();
        Session session3 = SessionUtil.getSession();
        //获取线程id
        long threadId = this.getId(); 
        //输出session的hashCode,分辨是否是同一个session实例
        System.out.println("线程" +threadId+ ":\n" 
                + session1.hashCode() + "\n" 
                + session2.hashCode() + "\n"
                + session3.hashCode());
    }

}

创建³³ Test.java的

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值