Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

说说synchronized关键字的底层原理是什么? #3

Open
oumaharuki opened this issue Feb 9, 2020 · 0 comments
Open

说说synchronized关键字的底层原理是什么? #3

oumaharuki opened this issue Feb 9, 2020 · 0 comments

Comments

@oumaharuki
Copy link
Owner

synchronized 同步语句块的实现使用的是 monitorenter 和 monitorexit 指令,其中 monitorenter 指令指向同步代码块的开始位置,monitorexit 指令则指明同步代码块的结束位置。
计数器加1,然后第二次synchronized那里,会再次获取myObject对象的monitor的锁,这个就是重入加锁了,然后计数器会再次加1,变成2。这个时候,其他的线程在第一次synchronized那里,会发现说myObject对象的monitor锁的计数器是大于0的,意味着被别人加锁了,然后此时线程就会进入block阻塞状态,什么都干不了,就是等着获取锁
`// 线程1

synchronized(myObject) { -> 类的class对象来走的

// 一大堆的代码

synchronized(myObject) {

// 一大堆的代码

}

}

`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant