This method is used to achieve static synchronization which locks a class, not an object.
Why use static synchronization?
Consider a shared class ‘Numbers’ for two objects (obj1 and obj2). The use of the synchronized method and synchronized block cannot interfere between the objects created(th1 and th2 or th3 and th4) for shared class because the lock was on the object. But interference may occur between th1 and th3 or th2 or th4 because of the class lock, th1 contain another class and th3 contain another class.
So to solve this interference we use Static Synchronization.
Java program to demonstrate the use of static synchronization:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | class Numbers { synchronized static void displaySum(int a) { for(int i=1;i<=4;i++) { System.out.println(a+i); try { Thread.sleep(200); }catch(Exception e) { System.out.println(e); } } } } class Thread1 extends Thread { Numbers n; Thread1(Numbers n) { this.n = n; } public void run() { n.displaySum(1); } } class Thread2 extends Thread { Numbers n; Thread2(Numbers n) { this.n = n; } public void run() { n.displaySum(10); } } class Thread3 extends Thread { Numbers n; Thread3(Numbers n) { this.n = n; } public void run() { n.displaySum(100); } } class Thread4 extends Thread { Numbers n; Thread4(Numbers n) { this.n = n; } public void run() { n.displaySum(1000); } } public class Main { public static void main(String args[]) { Numbers obj = new Numbers(); Thread1 th1=new Thread1(obj); Thread2 th2=new Thread2(obj); Thread3 th3=new Thread3(obj); Thread4 th4=new Thread4(obj); th1.start(); th2.start(); th3.start(); th4.start(); } } |
Output static synchronization:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 2 3 4 5 11 12 13 14 101 102 103 104 1001 1002 1003 1004 |