Synchronized block in java
It is a block of code which makes the program control takes over a single thread over multithreads in a critical region.
Why synchronized block?
- It deals with single thread. So, it improves the performance.
- Specific block is locked here. It considers a set of code instead of complete method.
- The race condition is effectively handled.
- Data inconsistency also improved.
How to create a synchronized block?
The code is given below.
Code:
synchronized (lockObject) {
// critical
section code
}
Let us create a java
program to implement the counting application using synchronized block.
Program:
- A class sample is created with private variable ‘s_incre’ and incre() function’s part of code as synchronized block.
- It increments the value ‘s_incre’. A function getIt() displays the counted value.
- In the main() function, object is created for sample class. Two threads are created with a loop of executions.
- Start the threads. Wait for finishing the processes. Finally, print the value.
Code:
class sample {
private int s_incr
= 0;
public void
incre() {
// synchronized
block
synchronized
(this) {
s_incr++;
}
}
public int getIt()
{
return s_incr;
}
}
class SampleCode2 {
public static void
main(String[] args) throws InterruptedException {
sample s1 =
new sample();
Thread t1 =
new Thread(() -> {
for (int i
= 0; i < 300; i++) {
s1.incre();
}
});
Thread t2 =
new Thread(() -> {
for (int i
= 0; i < 250; i++) {
s1.incre();
}
});
// Start the
threads
t1.start();
t2.start();
// Wait until
the threads are finish the process
t1.join();
t2.join();
// display the
counting value
System.out.println("The Final Count is: " + s1.getIt());
}
}
Output:
Compile and run the program to get the output.
C:\raji\blog>javac SampleCode2.java
C:\raji\blog>java SampleCode2
The Final Count is: 550
Yes. The java program to use synchronized block concept is done
and it is executed with sample input and outputs. Hope, this code is easy for
you.Keep coding!!!
Comments
Post a Comment