当前位置:网站首页>Synchronized同步锁的基本原理
Synchronized同步锁的基本原理
2022-07-23 21:15:00 【斯沃福德】
Java内存模型回顾:

- Java所有变量都存储在主内存中
- 每个线程都有自己独立的工作内存,里面保存该线程的使用到的变量副本(该副本就是主内存中该变量的一份拷贝)
- 线程对共享变量的所有操作都必须在自己的工作内存中进行,不能直接在主内存中读写
- 不同线程之间无法直接访问其他线程工作内存中的变量,线程间变量值的传递需要通过主内存来完成。
线程1对共享变量的修改,要想被线程2及时看到,必须经过如下2个过程:
①把工作内存1中更新过的共享变量刷新到主内存中
②将主内存中最新的共享变量的值更新到工作内存2中
Synchronized同步锁:
Synchronized同步锁主要以阻塞的方式保证数据的原子性;
也可以保证可见性:线程在加锁时,先清空工作内存→在主内存中拷贝最新变量的副本到工作内存→执行完代码→将更改后的共享变量的值刷新到主内存中→释放互斥锁。
原理:
- 每个Java对象都关联了一个monitor对象,加synchronized和关键字后 monitor对象会生效,通过进入与退出Monitor对象实现互斥、同步功能;
- monitor中划分为 Owner 表示监视器的所有者,同时刻只能有一个线程成为Owner ;
- 刚开始 Monitor 中 Owner 为 null,当线程t1访问对象时发现Owner为空,则会执行Monitor.Enter指令,线程会占据这个对象的Owner;
- 当线程t2来访问对象发现Owner已经被锁住了,则t2会进入EntryList排队等待(阻塞状态),当t1执行完毕会执行Monitor.Exit 命令,线程释放对象的Owner,通知EntryList的线程去争抢Owner

锁重入:
对同一个都对象多次执行Monitor.Enter--------锁重入
为了避免锁重入增大开销,可以让synchronized锁住的粒度大一些,减少了Monitor.Enter和Monitor.Exit的次数
注意:
1.synchronized( )内要放引用类型的对象,不能放基本类型,
2.不加 synchronized 的对象不会关联监视器
边栏推荐
- Protocol buffers 的问题和滥用
- Stm32c8t6 driven lidar (I)
- Green-Tao 定理的证明 (1): 准备, 记号和 Gowers 范数
- LeetCode热题 HOT52-100
- Basic syntax of MySQL DDL and DML and DQL
- 【攻防世界WEB】难度四星12分进阶题:FlatScience
- 1062 Talent and Virtue
- Synchro esp32c3 Hardware Configuration Information serial port Print Output
- (note) learning rate setting of optimizer Adam
- 最小生成树:Prim
猜你喜欢
随机推荐
Read the five flow indicators of R & D efficiency insight
221. 最大正方形 ●● & 1277. 统计全为 1 的正方形子矩阵 ●●
2022.7.22 JS object
[continuous update] collection of raspberry pie startup and failure series
对接湖南CA使用U_KEY登录
[attack and defense world web] difficulty four-star 12 point advanced question: confusion1
2022.7.22 js对象
From which dimensions can we judge the quality of code? How to have the ability to write high-quality code?
Install under win7-vs2012 Net framework work
高数下|二重积分的计算4|高数叔|手写笔记
221. Largest square ● &1277. Square submatrix with statistics all 1 ● ●
[100 cases of scratch drawing] Figure 46-scratch drawing flowers children's programming scratch programming drawing case tutorial grade examination competition drawing training case
当我们在谈论陈春花和华为时,我们到底在讨论什么?
UnauthorizedAccessException:Access to the path “/xx/xx.xx“ is denied
Vrrp+mstp configuration details [Huawei ENSP experiment]
TypeScript基础
【微信小程序】你了解小程序开发吗?
Chapter1 数据清洗
STM32C8t6 驱动激光雷达实战(二)
ES6特性:Promise(自定义封装)







