Hibernate之悲观锁【共享锁、排他锁】

共享锁【写锁】少用

共享锁的现象:注意,操作要快,不然会超时

1、分别打开两个Mysql命令行 A和B


image.png

2、使用相同数据库
3、A和B依次输入 start transaction;
4、A和B查询相同表 select * from 表名 lock in share mode;
5、A 输入更新语句, B 输入更新语句【总之会有一方卡住】


image.png

卡住的原因是一方拿到了共享锁,拿到共享锁的一方提交事务【commit】后另一方才可以执行;

排他锁【写锁】常用锁行,不建议锁表

1、分别打开两个Mysql命令行 A和B
2、使用相同数据库
3、A和B依次输入 start transaction;
4、A输入select * from t_customer for update ;【锁表】后,发现界面输出;
5、B输入select * from t_customer for update ;【锁表】后,界面无输出;


image.png

6、A提交事务【commit】后,B有输出


image.png

7、执行锁行操作A输入select * from t_customer where id=1 for update ;【锁表】后,发现界面输出;
8、B执行select * from t_customer where id=2 for update ;有输出
image.png

9、B执行select * from t_customer where id=1 for update ;卡住
image.png

10、A提交事务【commit】后,B执行select * from t_customer where id=1 for update ;输出
image.png

Hibernate写锁【排他锁】实现

现象:命令行开启线程,应用程序开启线程

1、命令行就绪


image.png

2、执行应用程序


image.png

3、应用程序输出【卡住】
image.png

3、命令行提交事务【commit】


image.png

4、查看应用程序控制台


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容