0
点赞
收藏
分享

微信扫一扫

乐观锁,悲观锁

少_游 2022-03-12 阅读 39

1、悲观锁
当数据库中一条数据进行修改的时候,为避免同时被其他线程修改,直接对我要修改的数据进行上锁(表锁,行锁),等本线程操作结束之后释放锁,类似于java中直接使用同步 synchronized 关键字

案例:

//1.开启事务
begin;
//2.查询数据上锁
select id from table where id = 1 for udate
//3.数据修改操作
update table set num=1 where id =1
//4.提交事物释放锁
commit



2、乐观锁

使用版本控制的方法


//1.已有数据
id = 1 ,version = 1 ,num = 1
//2.线程1
//读取数据时 version = 1
update table set num=num+1 where id =1 and version = 1
//3.线程2
//读取数据时 version = 1
update table set num=num+1 where id =1 and version = 1
//线程1和线程2必定只有一个能成功,保证了数据的一致性

举报

相关推荐

0 条评论