Java Static Synchronization
When a static method is synchronized, then the lock will be on the class not on the object.
Syntax
synchronized static Method_Name() {
// statements
}

Problem
If you're using two objects object1 and object2 which shared the class. In this situation, D1 and D2 or D3 and D4 didn't interfere because of the synchronized method. But D1 and D3, or D2 and D4 can be interference because of D1 or D2 acquires the lock and D3 or D4 acquires another lock. To solve this problem static synchronization is needed.
Example:
class Calculate {
synchronized static void show(int n) {
try {
for(int i=1;i<=3;i++){
System.out.println(n*i);
Thread.sleep(500);
}
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
class Data implements Runnable {
int n;
Calculate ca;
Thread t;
public Data(Calculate c, int num) {
ca = c;
n = num;
t = new Thread(this);
t.start();
}
public void run() {
ca.show(n);
}
}
public class StaticSynchronization{
public static void main(String args[]) {
Calculate ca = new Calculate();
Data d1= new Data(ca, 10);
Data d2= new Data(ca, 100);
try {
d1.t.join();
d2.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com