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

String Pattern Programs in C

In this tutorial, we will write various C pattern programs for String. Before that, you may go through the following topics in C. for loop …
Read More

Java Program to Find pair of Integers in Array whose sum is given Number

In this tutorial, we will write a program to find a pair of elements from an array whose sum equals a given number in java …
Read More

Program to Print Diamond Alphabet Patterns in C

In this tutorial, we will learn to write a C program to print Diamond patterns using alphabets/characters. However, in this tutorial, we will create a …
Read More

Half Diamond Pattern in C using Alphabets

In this tutorial, we will learn and code the half diamond alphabet patterns in C programming language. However, in this tutorial, we will create a …
Read More

Half Pyramid of Alphabets in C

In this tutorial, we will learn and code alphabet patterns in C programming language specifically the Half pyramid of alphabets in C programming. However, in …
Read More

Inverted Half Pyramid Pattern of Alphabets in C

In this tutorial, we will write a C program to print half Pyramid using alphabets/characters. Before that, you may go through the following topic in …
Read More