I would like to clear few doubts and extending question from here - synchronization in two methods in the same class.
public class Demo {
public synchronized void methodA(){
System.out.println("Method A");
}
public synchronized void methodB(){
System.out.println("Method B");
}
public static void main(String[] args) {
Demo demo = new Demo();
Demo demo1 = new Demo();
Thread thread1 = new Thread(() -> demo.methodA());
thread1.start();
Thread thread2 = new Thread(() -> demo1.methodB());
thread2.start();
}
}
locks work at the instance level, not at the class level.
Case-1: For each instance of Demo
at most one between method1 and method2 can be running at any given moment. This is clear.
Case-2: Two different instances are calling two separate method, will still the thread block each other?
Using Static Synchronized the same method -
public class Demo {
public static synchronized void methodA(){
System.out.println("Method A");
}
public static synchronized void methodB(){
System.out.println("Method B");
}
public static void main(String[] args) {
Demo demo = new Demo();
Demo demo1 = new Demo();
Thread thread1 = new Thread(() -> demo.methodA());
thread1.start();
Thread thread2 = new Thread(() -> demo1.methodB());
thread2.start();
}
}
Case-3: Say same instance of demo class demo
is used to call two separate method, will they block each other?
Case-4: Say different instances of Demo class demo
and demo1
is used to call two separate method will they still block each other?