编写原因:当使用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();
}
}