Introduction
Multi-threaded programs frequently encounter situations when numerous threads attempt to access the same resources, resulting in erroneous and unexpected outcomes. When resources can be accessed concurrently, they can be used in an inconsistent fashion. To prevent this, we must control the access using the synchronization techniques.
To get a general idea about the problems that we will encounter without synchronization in multi-threaded programs, please refer to this blog, Synchronization in Java. This blog discusses Synchronization in general and discusses one of the techniques to achieve Synchronization in Java - Synchronized Methods.
Also Read About, Multithreading in java
Java Synchronized Block
In this blog, we will discuss one of the techniques offered in Mutual Exclusion to keep threads mutually exclusive. Mutual Exclusion helps keep threads from interfering with one another while sharing data. It can be achieved by using the following three ways:
- By Using Synchronized Method
- By Using Synchronized Block
- By Using Static Synchronization
In this blog, we will take up the method of Synchronized Blocks to achieve the principle of Mutual Exclusion in Multi-threading.
Synchronized block can be used to perform synchronization on any specific resource of the method. Suppose we have 20 lines of code in our method, but we want to synchronize only 10 lines, in such cases, we can use a synchronized block.
If we put all the codes of the method in the synchronized block, it will work the same as the synchronized method.
Program
//example of java synchronized method
class ResourceClass {
int resource;
ResourceClass(int val) {
this.resource = val;
}
void UpdateandPrintResource(int n, int threadNum) {
// Non-Synchronized Block
System.out.println("Thread " + threadNum + " in non-synchronized block.");
// Synchronized Block
synchronized (this) {
System.out.println("Thread " + threadNum + " Starts in Synchronized Block....");
this.resource += n;
try {
Thread.sleep(400);
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Value of Resource: " + this.resource);
System.out.println("Thread " + threadNum + " Ends in Synchronized Block....");
}
}
}
class T1 extends Thread {
ResourceClass t;
T1(ResourceClass t) {
this.t = t;
}
public void run() {
t.UpdateandPrintResource(5, 1);
}
}
class T2 extends Thread {
ResourceClass t;
T2(ResourceClass t) {
this.t = t;
}
public void run() {
t.UpdateandPrintResource(10, 2);
}
}
public class TestSynchronization {
public static void main(String args[]) {
ResourceClass resoruceInst = new ResourceClass(10);
T1 t1 = new T1(resoruceInst);
T2 t2 = new T2(resoruceInst);
t1.start();
t2.start();
}
}
Output
Practice it on online java compiler for better understanding.
Must Read Static Blocks In Java.