![]() |
VOOZH | about |
Thread synchronization in Java is a mechanism used to control the access of multiple threads to shared resources to avoid data inconsistency. It ensures that only one thread executes a critical section at a time, preventing race conditions.
Imagine multiple computers connected to a single printer:
In Java, thread priorities determine the execution order, allowing higher-priority threads to preempt lower ones and access resources first. However, when threads of equal priority compete for the same resource, conflicts can lead to inconsistent or erroneous outcomes.
Thread synchronization are of two types:
While sharing any resource, this will keep the thread interfering with one another i.e. mutual exclusive. We can achieve this via
1. Synchronized Method
We can declare a method as synchronized using the synchronized keyword. This will make the code written inside the method thread-safe so that no other thread will execute while the resource is shared.
Implementation:
We will be proposing prints the two threads simultaneously showing the asynchronous behavior without thread synchronization.
Example 1: Here, we will use non-synchronized method.
Output:
Now using synchronized method, it will lock the object for the shared resource and gives the consistent output.
Example 2: Below example, lock the object for the shared resource.
Output:
2. Synchronized Block
If we declare a block as synchronized, only the code which is written inside that block is executed sequentially not the complete code. This is used when we want sequential access to some part of code or to synchronize some part of code.
Syntax:
synchronized (object reference)
{
// Insert code here
}
Example:
Output:
3. Static Synchronization
In this, the synchronized method is declared as "static" which means the lock or monitor is applied on the class not on the object so that only one thread will access the class at a time.
Example:
Output: