In Java Synchronization is the capability to control the access of multiple threads to any shared resource. In Java Synchronization is better option where we want to allow only one thread to access the shared resource.
The synchronization is mainly used to1. thread interference.
The synchronization is mainly two types1. Process Synchronization
Discuss only thread synchronization.
There are two types of thread synchronization mutual exclusive and inter-thread communication.
Mutual Exclusive helps keep threads from interfering with one another while sharing data. This can be done by three ways in java:
Synchronization is built around an internal entity known as the lock or monitor. Every object has an lock associated with it. By convention, a thread that needs consistent access to an object's fields has to acquire the object's lock before accessing them, and then release the lock when it's done with them.
From Java 5 the package java.util.concurrent.locks contains several lock implementations.
In this example, there is no synchronization, so output is inconsistent. Let's see the example: