同步函数和同步块有什么区别?
有什么区别
public synchronized void addition()
{
//something;
}
和 如果我错了和
public void addtion()
{
synchronized (//something)
{
//something;
}
}
忽略这个问题。
what is the difference between
public synchronized void addition()
{
//something;
}
and
public void addtion()
{
synchronized (//something)
{
//something;
}
}
If I am wrong Ignore this question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
相当于
现在,如果您将
this
替换为不同的对象引用,则将使用该其他对象的监视器来完成锁定。is equivalent to
Now, if you replace the
this
with a different object reference, the locking will be done using that other object's monitor.第二个无法编译。如果你的意思是
那么它们是等价的。
The second one doesn't compile. If you meant
Then they're equivalent.
如果第二个示例是
synchronized (this)
,那么就没有区别。如果是别的东西,那么锁的对象就不同了。If the second example is
synchronized (this)
, then there's no difference. If it's something else, then the lock object is different.与以下内容相同:
然而,在第二个示例中,您可能希望使用与
this
不同的内容进行同步。is the same as:
Whereas, in your second example, you may want to synchronize using something different from
this
.在第一个方法中,一次只有一个线程可以执行整个方法,而在第二个方法中,如果不使用 this 作为参数,则只有一个线程可以执行该同步块。
这是它的副本 使用同步方法而不是同步块有优势吗?< /a>
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?
同步方法在“this”对象上同步。如果它是一个块,您可以选择任何对象作为锁。
Synchronized method synchronizes on "this" object. And if it is a block you can choose any object as a lock.
I)
II)
在版本 I(
方法级同步
)中,一次完整的方法体只能由一个线程执行。但是,版本 II 更加灵活,因为它称为块级同步,您可以在
synchronized (//something)
上面添加一些行来并行执行它们。它应该是synchronized (this)
版本 II 应该是首选,因为只有该代码需要多线程(在同步内),这是至关重要的。
I)
II)
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 abovesynchronized (//something)
to execute them parallely. it should besynchronized (this)
version II should be preferred as only that code needs to be multithreaded (within synchronized) which are critical.