简体   繁体   English

获取另一个对象在同步块上的锁

[英]acquiring the lock of another object on a synchronized block

i'm currently studying the multithreading concept thoroughly and i'v noticed that whenever a synchronized block is discussed, the lock on this object is acquired. 我目前正在深入研究多线程概念,并且我注意到,每当讨论synchronized block时,都会获得this对象的锁定。 eg: 例如:

synchronized(this) {}

but, is there any reason to give another object as the argument for synchronized? 但是,是否有任何理由将另一个对象作为同步的参数? or is it an inadvisable pattern? 还是不明智的模式?

You can use a common object as follows. 您可以按以下方式使用公共对象。

static final Object lock=new Object();

Then you can parse this into synchronized block as follows 然后您可以将其解析为同步块,如下所示

synchronized(lock){

 }

Only requirement here is you have to share common object. 这里唯一的要求是您必须共享公共对象。 Then each path(different object) locked based on this object. 然后,基于此对象锁定每个路径(不同的对象)。

I think you are having issue with why we use other object. 我认为您对我们为什么使用其他对象有疑问。

If we want to locked different path by different Threads we have to locked each path. 如果要通过不同的线程锁定不同的路径,则必须锁定每个路径。 So we have to use third object. 因此,我们必须使用第三个对象。 Then when one object quires that lock object other threads has to wait until that lock is resealed. 然后,当一个对象要求该锁对象时,其他线程必须等待,直到该锁被重新密封为止。 But same thread which acquire the lock can continue. 但是获得锁的相同线程可以继续。

You can use a third party object as a lock . 您可以将第三方对象用作锁 Generally such objects can be used to achieve synchronization to shared resources between different objects , which will be forced to acquire this third party object lock before executing certain piece of code. 通常,此类对象可用于实现对不同对象之间共享资源的同步 ,这将被迫在执行某些代码段之前获取此第三方对象锁。

An example why locking on something else might be beneficial: 为什么锁定其他内容可能会有所帮助的示例:

final List<Object1> firstList = new List<>();
final List<Object2> secondList = new List<>();

// ...

public Object readFromListOne() {
  synchronized(firstList) {
    return firstList.remove(0);
  }
}

public Object readFromListTwo() {
  synchronized(secondList) {
    return secondList.remove(0);
  }
}

Here threads can access both lists simultaneously, while a synchronized(this) would have locked both calls, even though it isn't necessary. 在这里线程可以同时访问两个列表,而synchronized(this)可以锁定两个调用,即使这不是必需的。

Btw: a concurrent list will render all this synchronization obsolete 顺便说一句:并发列表将使所有这些同步过时

synchronized(this) {}

That means that any other thread that synchronizes on this will have to release/wait until you release/wait the lock before it can proceed. 这意味着,任何其他线程上进行同步this释放/等待 ,直到你释放/等待锁才能进入。

  synchronized(somethingElse) {}

That means the lock happens on now with somethingElse . 这意味着现在可以使用somethingElse进行锁定。

So there is a clear difference and depends on what you are synchronized. 因此,两者之间存在明显的差异,具体取决于您所同步的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM