Java Static Synchronization
When Synchronization is applied on a static Member or a static block, the lock is performed on the Class and not on the Object, while in the case of a Non-static block/member, lock is applied on the Object and not on class.
Java Static Synchronization : Example
class TableClass { synchronized static void displayTable(int n) { for (int i = 1; i <= 4; i++) { System.out.println(n * i); try { Thread.sleep(200); } catch (Exception e) { } } } } class MyThread1 extends Thread { public void run() { TableClass.displayTable(1); } } class MyThread2 extends Thread { public void run() { TableClass.displayTable(10); } } class MyThread3 extends Thread { public void run() { TableClass.displayTable(100); } } class MyThread4 extends Thread { public void run() { TableClass.displayTable(1000); } } class SynchronizeExample { public static void main(String args[]) { MyThread1 t1 = new MyThread1(); MyThread2 t2 = new MyThread2(); MyThread3 t3 = new MyThread3(); MyThread4 t4 = new MyThread4(); t1.start(); t2.start(); t3.start(); t4.start(); } }
Output :
1 2 3 4 1000 2000 3000 4000 10 20 30 40 100 200 300 400