Java Class Level Synchronization

Class Level lock can be achieved by using two keywords static and synchronized in any method signature. But Object level lock can be achieved by using synchronized keyword or block, there can be multiple Objects for a particular class but only one class will be available for any Java application with unique name.

Synchronization in java works in two ways, one is Object Level Synchronization and other one is Class Level Synchronization. Class level synchronization requires a Class level lock and Object Level Synchronization requires an Object level lock.

Class Synchronization example

public class ClassLevelLockingExample extends Thread {

	public static void main(String[] args) {
		Thread t1 = new ClassLevelLockingExample();
		Thread t2 = new ClassLevelLockingExample();
		t1.start();
		t2.start();
	}

	public void run() {
		ClassLevelLockingExample.classLevelLockMethod();
	}

	private static synchronized void classLevelLockMethod() {
		try {
			System.out.println("Entered into the Class Level Lock Method");
			Thread.sleep(10000);
			System.out.println("After this Statement Only Any Other thread can enter this method");
		} catch (InterruptedException e) {

			e.printStackTrace();
		}

	}
}