Java – Thread Synchronization3 min read

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 a lock when it invokes the synchronized method and releases when the work is done.

Syntax for Synchronized method:

Example of Java program 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 in Java:

Output:

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


MORE

Implement Insertion sort Program in C

In this tutorial, we will learn and write a C program to implement insertion sort. Before that you may go through the following topics in …
Read More

C Program for implementation of Selection sort

In this tutorial, we will learn and write a C program to implement selection sort using function. Before that you may go through the following …
Read More

C Program to Delete a Particular element from an Array

In this tutorial, we will write a C program to delete an element in an array by specifying the value. Before that, you should have …
Read More

C Program to sort a String in Ascending order

In this tutorial, we will write a c program to sort a string array in ascending order. Before that, you may go through the following …
Read More

C Program to find Maximum occurring Character in a String

In this tutorial, we will write a program in C to find the maximum occurring character in a string. Before that, you may go through …
Read More

Keith Number Program in C

In this tutorial, we will write a Keith number in C. It is one of the most asked questions in an interview. Before that, you …
Read More