What is the difference between a synchronized function and synchronized block? [duplicate]

♀尐吖头ヾ 提交于 2020-01-19 17:36:46

问题


what is the difference between

public synchronized void addition()
{
   //something;
}

and

public void addtion()
{
     synchronized (//something)
     {
        //something;
     }
}

If I am wrong Ignore this question.


回答1:


it the first one only one thread can execute whole method at a time whereas in second one only one thread can execute that synchronized block if not used this as parameter.

here is a duplicate of it Is there an advantage to use a Synchronized Method instead of a Synchronized Block?




回答2:


public synchronized void addition() {...}

is equivalent to

public void addition() {
  synchronized(this) { ... }
}

Now, if you replace the this with a different object reference, the locking will be done using that other object's monitor.




回答3:


The second one doesn't compile. If you meant

public void addition()
{
     synchronized (this)
     {
        //something;
     }
}

Then they're equivalent.




回答4:


If the second example is synchronized (this), then there's no difference. If it's something else, then the lock object is different.




回答5:


public synchronized void addition()
{
   //something;
}

is the same as:

public void addtion()
{
     synchronized (this)
     {
        //something;
     }
}

Whereas, in your second example, you may want to synchronize using something different from this.




回答6:


Synchronized method synchronizes on "this" object. And if it is a block you can choose any object as a lock.




回答7:


I)

public synchronized void addition() 
{
    //something; 
}

II)

public void addtion() 
{      
    synchronized (//something)      
    {
        //something;      
    }
} 

In version I (method level synchronization), at a time, complete body of method can only be executed by one thread only.

however, version II is more flexible cause it's called block level synchronization and you can add some lines above synchronized (//something) to execute them parallely. it should be synchronized (this)

version II should be preferred as only that code needs to be multithreaded (within synchronized) which are critical.



来源:https://stackoverflow.com/questions/8519700/what-is-the-difference-between-a-synchronized-function-and-synchronized-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!