简体   繁体   English

同步对象:锁定代码与锁定对象

[英]Synchronized Object: Locking Code vs Locking Object

Suppose you have two threads that have access to the same public object. 假设您有两个线程可以访问同一公共对象。 One thread has a block of code that reads the object's fields. 一个线程具有一段代码,该代码块读取对象的字段。

synchronized(object)
{
    read object fields
}

While the read object field code is executing in thread 1, if thread 2 wants to update the object's fields, will it have to wait until thread 1 finishes reading the object's fields before updating (eg is the object locked from access by other threads while the synchronized code block is executing)? 当读取的对象字段代码在线程1中执行时,如果线程2要更新对象的字段,它将不得不等到线程1完成读取对象的字段之后再进行更新(例如,对象被锁定而不能被其他线程访问)同步代码块正在执行)?

Synchronizing on an object does not "lock" it in any way. 在对象上进行同步不会以任何方式“锁定”它。 Unless updating the object's fields is synchronized in the same fashion, it may very well interleave with the reading code you presented here. 除非以相同的方式同步更新对象的字段,否则它很可能与您在此处提供的阅读代码交错。

No, the second thread will not wait, unless it has a synchronized block on the same object too. 不,第二个线程不会等待,除非它在同一对象上也有一个synchronized块。

synchronized(object)
{
    // read object fields
}

... in other thread:

synchronized(object)
{
    // write object fields
}

Synchronized block only protects the code inside it. 同步块仅保护其中的代码。 So if two or more threads try to run code inside synchronized block (protected by same object monitor) they will be executed exclusively. 因此,如果两个或多个线程尝试在同步块(受同一对象监视器保护)中运行代码,则它们将被独占执行。 Meaning if one thread has entered synchronized block others will have to wait till it gets out. 这意味着如果一个线程进入了同步块,则其他线程将不得不等待直到退出。

Synchronized block does not lock the object in anyway, it just uses object's monitor to guard the code inside it. 无论如何,同步块不会锁定对象,它只是使用对象的监视器来保护其中的代码。 If you want to make method of object thread safe then you have to declare them synchronized. 如果要使对象线程的方法安全,则必须声明它们已同步。

synchronized getField()
synchronized setField()

Now getField() and setField() can safely be called by multiple threads. 现在,可以由多个线程安全地调用getField()和setField()。

However using synchronized has a performance cost instead you can try using Locks, or Atomic classes in java.util.concurrent.atomic like AtomicInteger, AtomicBoolean or AtomicReference. 但是,使用同步会降低性能,而您可以尝试使用Locks或java.util.concurrent.atomic中的 Atomic类,例如AtomicInteger,AtomicBoolean或AtomicReference。

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

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