Java Thread Synchronization

Having multiple threads in a program may cause inconsistency and thread interference, that is the multiple threads when trying to access the same resource. One thread may try to write and another may try to read the shared resource or same file. So to achieve the use of only one resource or file at a time, we use synchronization.

Synchronization makes sure that only one out of the multiple threads is allowed to access the resource at a given time.
In this process, comes the Lock Concept, also known as monitors.
Each object created in java is provided with the monitor. Only one thread may hold the lock at a time through which thread can lock or unlock.

Synchronized method in java:

Java contains a synchronized method to apply synchronous behaviour to the program. This method is used to lock an object for shared resources. The object automatically obtained lock when it invokes the synchronized method and releases when the work is done.

Syntax for Synchronized method:

Example without the use synchronized method:

Output:


Now let see an example with the use synchronized method:

Output:


Synchronized block in java:

It is also used to achieve synchronization in java which locks an object for any shared resource. It is the same as a synchronized method.
Using Synchronized block only selected lines of code can be synchronized.

Syntax for Synchronized block:

Example to demonstrate the use of Synchronized block:

Output:

Note that:
The scope of the synchronized method is higher than the synchronized block.