2

4. synchronized工作原理

 3 years ago
source link: http://sunliangliang.com/?p=43
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

4. synchronized工作原理

发表于 2021-03-17 | 分类于 并发编程 | 0 | 阅读次数 21

1.入门知识回顾

synchronized可以作用在对象实例和,类两者的区别

2.底层原理

核心原理是 monitorentermonitorexit两个指令

源文件

  • synchronized加锁的对象,都会有一个monitor计数器,从0开始,如果一个线程要获取monitor的锁,需要判定该值是否为0,若为0,则获取到锁,并将值+1,此时monitor=1.jvm会记录持有该锁的线程。
  • 并且monitor锁是可重入的,原理就是,获取锁的时候如果monitor不是1,会判定持有该锁的是否为当前线程,如果是的话对计数器是自增操作,此时monitor=2。
  • 如果出了synchronized修饰的代码片段,就会有一个monitorexit的指令,在底层会对monitor的计数器减一,如果多次重入就会对应多次减一,直到计数器是0
坚持有质量的创作,您的支持将支持我继续创作!

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK