当前位置:网站首页>synchronized 关键字和volatile关键字的作用和区别
synchronized 关键字和volatile关键字的作用和区别
2022-04-22 05:52:00 【肝铁侠】
synchronized
synchronized 关键字是解决并发问题常用解决方案,
有以下三种使用方式:
①同步普通方法,锁的是当前对象。
②同步静态方法,锁的是当前 Class 对象。
③同步块,锁的是 () 中的对象。
实现原理:
JVM 是通过进入、退出对象监视器( Monitor )来实现对方法、同步块的同步的。
具体实现是在编译之后在同步方法调用前加入一个 monitor.enter 指令,在退出方法和异常处插入 monitor.exit 的指令。
其本质就是对一个对象监视器( Monitor )进行获取,而这个获取过程具有排他性从而达到了同一时刻只能一个线程访问的目的。
而对于没有获取到锁的线程将会阻塞到方法入口处,直到获取锁的线程 monitor.exit 之后才能尝试继续获取锁。
volatile
volatile是Java提供的一种轻量级的同步机制。
创建一个对象有三个步骤:
①分配内存空间。
②初始化对象。
③将对象指向分配的内存地址。
加上 volatile 是为了让以上的三步操作顺序执行,否则有可能第三步在第二步之前被执行就有可能导致某个线程拿到的单例对象还没有初始化,导致使用报错。
比如说定义一个boolean变量flag,如果我们没有用volatile对其进行修饰的话,不会立即刷新到主内存中,当多线程进来取值的时候,你拿到的可能还是初始值。由此可以看出volatile能保证可见性,顺序性。
版权声明
本文为[肝铁侠]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_51250453/article/details/122158477
边栏推荐
- The difference between hash mode and history mode
- Redis持久化
- Asynchronous programming & concurrent asyncio
- 重磅!九州云获颁“2020年度运营商最佳合作伙伴”奖
- MySQL的InnoDB存储引擎
- 使用PG_STAT_REPLICATION监视复制
- Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: “/?k=“
- Pgbouncer最佳实践:系列一
- Promise
- TensorFlow 实现web人脸登录系统
猜你喜欢

async与await

JS debugging interference - infinite debugger bypass

Analysis and practice of open source at home and abroad

Promise

Focusing on the innovation and practice of edge computing, Kyushu cloud attended the 2021 China Unicom 5g MEC seminar

有一份@九州云OFFER在等你

Chemex

MySQL的InnoDB存储引擎

Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: “/?k=“

开源数据库管理系统现在比商业产品更受欢迎
随机推荐
恭喜! 中移动智家中心入选2020年度ICT行业龙虎榜
优秀 | 九州云入选首届混合云大会优秀案例及产业全景图
树的的遍历
Kyushu cloud passes the authoritative evaluation of EC ready edge cloud
数美科技CTO梁堃建议:技术+运营组合防控 “杀猪盘”
官宣|Skyline正式加入OpenStack官方模块
Kyushu cloud, the brand with the most investment value of the year, was selected into the "2021 new economy annual peak list" of AI media
Mysql gap lock引起的一个问题
Swing显示时间(点击一次显示一次)
Redis cluster III. cluster mode
C语言实现哈希字典及笔记
Nacos源码启动报错解决方法
A problem caused by MySQL gap lock
Internet noun quick search
JS reverse practice: analysis of Youdao translation interface
PostgreSQL 13.3、12.7、11.12、10.17和9.6.22发布了!
为PostgreSQL的表自动添加分区
Distributed transaction solution Seata
Evaluation of the first Avalon 1246-85t chassis with large computing power and low power consumption
Good news | Kyushu cloud was rated as "Zhejiang high tech enterprise research and development center"