3 回答
一只萌萌小番薯
TA贡献1795条经验 获得超7个赞
有人能通过一个例子告诉我同步方法相对于同步块的优势吗?谢谢。
this.
public synchronized void method() { // blocks "this" from here....
...
...
...} // to herepublic void method() {
synchronized( this ) { // blocks "this" from here ....
....
....
....
} // to here...}// locks the whole object... private synchronized void someInputRelatedWork() {
... }private synchronized void someOutputRelatedWork() {
... }// Using specific locksObject inputLock = new Object();Object outputLock = new Object();private void someInputRelatedWork() {
synchronized(inputLock) {
...
} }private void someOutputRelatedWork() {
synchronized(outputLock) {
...
}} private void method() {
... code here ... code here ... code here synchronized( lock ) {
... very few lines of code here }
... code here ... code here ... code here ... code here}
芜湖不芜
TA贡献1796条经验 获得超7个赞
'this'
synchronized void foo() {
...}void foo() {
synchronized (this) {
...
}}
蛊毒传说
TA贡献1895条经验 获得超3个赞
同步法
IDE可以指示同步方法。 语法更加简洁。 强制将同步块拆分为单独的方法。
同步到这一点,从而使局外人也有可能同步到它。 将代码移出同步块的难度更大。
同步块
允许对锁使用私有变量,从而迫使锁留在类中。 通过搜索对变量的引用可以找到同步块。
语法更复杂,因此代码更难阅读。
添加回答
举报
0/150
提交
取消
