同步方法和同步方法的代码块有什么区别?

来源:百度知道 编辑:UC知道 时间:2024/05/26 17:28:32
synchronized
同步方法和同步方法里面的代码块,有什么区别?
在什么情况下用哪一个?

synchronizing only block of code would be faster than synchronizing a whole method. since shared resource would be less so that the lock(monitor) would be released sooner.

synchronized 修饰的方法表示
同一时间只能有一个线程进入到这个方法的方法块里面
其他的线程需要等待直到占用的那个线程离开这个方法

一楼回答的很不错