Synchronized block
Declaring variables are not the only tool to ensure the 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 inside a method.
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 that 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 the block comes. The following small program demonstrates the synchronized
block:
public class SynchronizedDemo implements Runnable { Â Â Â public static final int N = 1000; Â Â Â public static final int MAX_TRY = 1_000_000...