hibernate 加锁
来源:互联网 发布:本地telnet不通80端口 编辑:程序博客网 时间:2024/05/16 15:24
- package com;
-
- import org.hibernate.LockMode;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.AnnotationConfiguration;
- import org.hibernate.cfg.Configuration;
-
-
- public class ThreadTest {
-
- private static Session session = HibernateUtil.currentSession();
-
- private class Lock1 implements Runnable {
-
- public void run() {
-
- Transaction t = session.beginTransaction();
- System.out.println("线程1查询中。。。加锁");
-
- Employee employee = (Employee) session.get(Employee.class, 2,
- LockMode.UPGRADE);
- try {
- Thread.sleep(10000);
- } catch (InterruptedException e) {
-
- e.printStackTrace();
- }
- t.commit();
- session.close();
- System.out.println("更新完成,减锁");
- }
- }
-
- private class Lock2 implements Runnable {
-
- public void run() {
-
- Transaction t = session.beginTransaction();
- System.out.println("线程2查询中。。。。。");
- Employee employee = (Employee) session.get(Employee.class, 2);
- System.out.println("线程2更新中。。。。。");
- employee.setEmployeeName("飞飞刘");
- session.update(employee);
- t.commit();
- session.close();
- }
-
- }
-
- public static void main(String[] args) {
- ThreadTest t = new ThreadTest();
- Lock1 l1 = t.new Lock1();
- Lock2 l2 = t.new Lock2();
- Thread thread1 = new Thread(l1);
- Thread thread2 = new Thread(l2);
- thread1.start();
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
-
- e.printStackTrace();
- }
- thread2.start();
- }
-
- }