Java synchronized
The primary means of ensuring mutual exclusion in Java is through synchronized methods.
methods
In Java, a method may be declared synchronized. In each object at most one synchronized method can run at any one time. We say that a synchronized method obtains a lock on its containing object before it can execute. Since there is only one lock for each object, this prevents any other synchronized method from running until this method completes: no other method can obtain a lock on the object until this method releases its lock. This one-animacy-running-at-a-time property is called mutual exclusion.
// statements
}
(blocks)
Java has a second form of synchronized execution. A special synchronized statement type can be used to provide mutual exclusion on its body. Unlike synchronized methods, the synchronized statement (sometimes called a synchronized block) must explicitly specify the object it locks. The syntax of this statement is:
public void methodB() {
// statements
synchronized ( objectReference ) { // statements }
}