当前位置:网站首页>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 的对象不会关联监视器
边栏推荐
- 1061 Dating
- scala编程(初级)
- Minimum spanning tree: Kruskal
- 最小生成树:Prim
- KubeVela离线安装
- An interview question about common pitfalls in golang for range
- Network learning infrared module, 8-way emission independent control
- If the order is not paid within 30 minutes, it will be automatically cancelled
- 做一个有职业操守的软件匠人
- High numbers | calculation of triple integral 2 | high numbers | handwritten notes
猜你喜欢
![[wechat applet] do you know about applet development?](/img/3d/da58255aeb6bf6bc5021d988906bcc.png)
[wechat applet] do you know about applet development?

OpenCV图像处理——拉普拉斯金字塔

High numbers | calculation of triple integral 2 | high numbers | handwritten notes

做一个有职业操守的软件匠人

合宙ESP32C3硬件配置信息串口打印輸出

SQLite database

Protocol buffers 的问题和滥用

【持续更新】树莓派启动与故障系列集锦

Synchro esp32c3 Hardware Configuration Information serial port Print Output

Typescript Basics
随机推荐
Detailed explanation of MSTP protocol for layer 3 switch configuration [Huawei ENSP experiment]
告诉我十大证券公司?请问网上开户安全么?
Minimum spanning tree: Kruskal
Chapter1 数据清洗
"Pulse" to the future! Huawei cloud Mrs helps smooth migration to the cloud
模块化开发
Unity solves that animation is not available: the animationclip 'xxx' used by the animation component 'xxx' must be marked as legacy
TCP半连接队列和全连接队列(史上最全)
SQLite数据库
一时跳槽一时爽,一直跳槽一直爽?
Green-Tao 定理的证明 (2): Von Neumann 定理的推广
Green-Tao 定理 (4): 能量增量方法
【着色器实现RoundWave圆形波纹效果_Shader效果第六篇】
ES6 feature: Promise (custom encapsulation)
对接湖南CA使用U_KEY登录
深入浅出边缘云 | 1. 概述
[shader realizes roundwave circular ripple effect _shader effect Chapter 6]
确定括号序列中的一些位置
LeetCode_ 376_ Wobble sequence
做一个有职业操守的软件匠人