Synchronization in java
Synchronization is a method which makes the one thread can access the shared resource at a time. The shared resource can be a variable, object or methods. The shared data can be used effectively.
Features:
The features are given below.
- ·
Data
integrity.
- ·
Thread
safety is achieved.
- ·
Race
condition is effectively handled.
- ·
It
prevents data inconsistency.
Let us create
a synchronized block in java.
Program:
To create synchronization in java
- This program creates a class for thread which is “Th_Sample”. It has two methods “incre()” and “getIt()”.
- “incre()” method is used to increment the value.
- “getIt()” method gets the input value.
- Next, a main class is created as “S_Sample”.
- The object for Th_sample is created.
- Two thread objects are created. Each one has separate for loop to count the value.
- Start the two threads. Using try,catch block, run the threads.
- Finally,print the value.
Code:
class
Th_Sample{
// The Shared variable is named as ‘x’.
private int x = 0;
// Synchronized method to increase the
value
public synchronized void incre(){
x++;
}
// Synchronized method to get the input
public synchronized int getIt(){
return x;
}
}
public
class S_Sample{
public static void main(String[] args){
//
Shared resource between threads
Th_Sample s1 = new Th_Sample();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 300; i++)
s1.incre();
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++)
s1.incre();
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("The Counter
value is : " + s1.getIt());
}
}
Output:
Compile and
run the program to get the output.
C:\raji\blog>javac S_Sample.java
C:\raji\blog>java S_Sample
The
Counter value is : 1300
The synchronization
in java with sample code is explained here. Hope, this code is useful to you. Keep
Coding!!!!
Comments
Post a Comment