synchronized(this)阻止整个对象? [英] synchronized(this) blocks whole object?

查看:117
本文介绍了synchronized(this)阻止整个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

synchronized block vs synchronized method?

从接受的答案到这个问题:在Java关键部分,我应该同步什么在?
我了解到

From accepted answer to this question: In Java critical sections, what should I synchronize on? I learn that

public synchronized void foo() {
    // do something thread-safe
}

和:

public void foo() {
    synchronized (this) {
        // do something thread-safe
    }
}

做同样的事情。但是在第一种情况下,我们只对一个对象的方法进行同步,而在第二种情况下,我们使得不可访问的整个对象。那么为什么这两个代码片段会做同样的事情呢?

do exactly the same thing. But in first case we make synchronized only one method of object, and in second case we make inaccessible Whole object. So why this two code snippests do same things?

推荐答案

你好像混在一起。

首先

public synchronized void method() {
}

从同步的角度来看是等价的:

is equivalent, from a synchronization perspective, to:

public void method() {
    synchronized (this) {
    }
}

已经提到了优点/缺点,各种副本提供了更多信息。

The pros / cons have already been mentioned and the various duplicates give more information.

其次,

synchronized(someObject) {
    //some instructions
}

表示同步块中的指令不能由2个线程同时执行,因为它们需要在 someObject 上获取监视器才能执行此操作。 (这假设someObject是一个不会改变的最终引用)。

means that the instructions in the synchronized block can't be executed simultaneously by 2 threads because they need to acquire the monitor on someObject to do so. (That assumes that someObject is a final reference that does not change).

在你的情况下, someObject 碰巧是这个

In your case, someObject happens to be this.

对象中任何未同步的代码仍然可以同时执行,即使监视由一个线程保存,因为它正在运行synchronized块。换句话说, synchronized(this)不会锁定整个对象。它只能防止2个线程同时执行同步块。

Any code in your object that is not synchronized, can still be executed concurrently, even if the monitor on this is held by a thread because it is running the synchronized block. In other words, synchronized(this) does NOT "lock the whole object". It only prevents 2 threads from executing the synchronized block at the same time.

最后,如果你有两个 synchronized 方法(都使用 this 作为锁),如果一个线程(T1)获取的锁来执行一个在这两种方法中,没有其他线程可以执行任何这两种方法,因为它们需要获取这个的锁,已经由T1持有。

Finally, if you have two synchronized methods (both using this as a lock), if one thread (T1) acquires a lock on this to execute one of those 2 methods, no other thread is allowed to execute any of the two methods, because they would need to acquire the lock on this, which is already held by T1.

这种情况可能会在关键部分产生争用,在这种情况下必须使用更精细的锁定策略(例如,使用多个锁) 。

That situation can create contention in critical sections, in which case a more fine grained locking strategy must be used (for example, using multiple locks).

这篇关于synchronized(this)阻止整个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆