hibernate 加锁

来源:互联网 发布:本地telnet不通80端口 编辑:程序博客网 时间:2024/05/16 15:24
  1. package com;   
  2.   
  3. import org.hibernate.LockMode;   
  4. import org.hibernate.Session;   
  5. import org.hibernate.SessionFactory;   
  6. import org.hibernate.Transaction;   
  7. import org.hibernate.cfg.AnnotationConfiguration;   
  8. import org.hibernate.cfg.Configuration;   
  9.   
  10.   
  11. public class ThreadTest {   
  12.   
  13.     private static Session session = HibernateUtil.currentSession();   
  14.   
  15.     private class Lock1 implements Runnable {   
  16.   
  17.         public void run() {   
  18.             // TODO Auto-generated method stub   
  19.             Transaction t = session.beginTransaction();   
  20.             System.out.println("线程1查询中。。。加锁");   
  21.             // 线程1加锁查询   
  22.             Employee employee = (Employee) session.get(Employee.class2,   
  23.                     LockMode.UPGRADE);   
  24.             try {   
  25.                 Thread.sleep(10000);   
  26.             } catch (InterruptedException e) {   
  27.                 // TODO Auto-generated catch block   
  28.                 e.printStackTrace();   
  29.             }   
  30.             t.commit();   
  31.             session.close();   
  32.             System.out.println("更新完成,减锁");   
  33.         }   
  34.     }   
  35.   
  36.     private class Lock2 implements Runnable {   
  37.   
  38.         public void run() {   
  39.             // TODO Auto-generated method stub   
  40.             Transaction t = session.beginTransaction();   
  41.             System.out.println("线程2查询中。。。。。");   
  42.             Employee employee = (Employee) session.get(Employee.class2);   
  43.             System.out.println("线程2更新中。。。。。");   
  44.             employee.setEmployeeName("飞飞刘");   
  45.             session.update(employee);   
  46.             t.commit();   
  47.             session.close();   
  48.         }   
  49.   
  50.     }   
  51.   
  52.     public static void main(String[] args) {   
  53.         ThreadTest t = new ThreadTest();   
  54.         Lock1 l1 = t.new Lock1();   
  55.         Lock2 l2 = t.new Lock2();   
  56.         Thread thread1 = new Thread(l1);   
  57.         Thread thread2 = new Thread(l2);   
  58.         thread1.start();   
  59.         try {   
  60.             Thread.sleep(1000);   
  61.         } catch (InterruptedException e) {   
  62.             // TODO Auto-generated catch block   
  63.             e.printStackTrace();   
  64.         }   
  65.         thread2.start();   
  66.     }   
  67.   
  68. }  
原创粉丝点击