Java's Synchronized
When the task is to execute the Syschronized method, this object is locked, and the other synchronized methods on that object will only be called until the previous method call is complete and the lock is freed.
class Demo{ synchronized void a(); syschronized void b();}如果a被调用并且没有被释放,此时调用b,是不能执行的,只有等待a执行完,才可以被调用
For a particular object, all of its synchronized methods share a lock, which can be used to prevent multiple tasks from accessing the encoded object memory at the same time.
If you synchronize with this in a method block, the effect of the critical section is reduced directly to the range of synchronization
class Demo{ Object o ; public Demo(){ o = this; } synchronized void a(){ } void b(){ synchronized(o){ } }
}
Summarize:
- When two concurrent threads access the same object in the synchronized (this) synchronization code block, only one thread can be executed within a single time. The other thread must wait for the current thread to finish executing the block before it can execute the code block.
- However, when a thread accesses one synchronized (this) of object to synchronize a block of code, another thread can still access the non-synchronized (this) synchronous code block in that object.
- In particular, when a thread accesses one of the synchronized (this) synchronization blocks of object, the access of other threads to all other synchronized (this) synchronization blocks in object is blocked.
- The third example also applies to other synchronous code blocks. That is, when a thread accesses a synchronized (this) of object to synchronize a block of code, it obtains the object lock of the objects. As a result, other threads are temporarily blocking access to all of the synchronization code portions of the object.
- The above rules also apply to other object locks.
For more details:
Java's Synchronized