HTML Java

Java Class Lock


Class level locking on synchronize method

If Synchronize method is static method then, we need to lock the class. In this example class is lock for a specific thread until all the operation perform in synchronized area. The class will be locked for thread t1 after that class locked for t2 you can see the below example;

Show.java

package DemoThreads;
class Show{
public static synchronized void goodMorning(String name) {
for(int i = 0 ;i < 2 ;i++) {
System.out.println("Good Morning "+name);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

MyThread.java

class MyThread extends Thread {
String name;
MyThread(String name) {
this.name = name;
}
public void run() {
Show.goodMorning(name);
}
}

Threads.java

public class Threads{
public static void main(String args[]) throws InterruptedException {
Show s = new Show();
MyThread t1 = new MyThread("ankit");
MyThread t2 = new MyThread("agam");
t1.start();
t2.start();
}
}

Output

Good Morning ankit
Good Morning ankit
Good Morning agam
Good Morning agam

Note : Every java class file has 1 variable name called class and it stores all the info and created by JVM, so 2 locks are available 1 is this(or object) lock and another is class lock. Both the lock is created by JVM.