Declaring variables is not the only tool for ensuring consistency between threads. There are other tools in the Java language, and one of them is the synchronized block. The synchronized keyword is part of the language and it can be used in front of a method or a program block, which is inside a method, constructor, or initializer block.
Every object in the Java program has a monitor that can be locked and unlocked by any running thread. When a thread locks a monitor, it is said that the thread holds the lock, and no two threads can hold the lock of a monitor at a time. If a thread tries to lock a monitor that is already locked, it gets BLOCKED until the monitor is released. A synchronized block starts with the synchronized keyword, and then an object instance specified between parentheses, and then blocking takes place. The following small program demonstrates...