I'm new to Java concurrency and I know that an instance method synchronized means that only one thread can execute that method at a time. But does this thing depends on the monitor object or not? Could 2 threads execute the same synchronized instance method in the same time if the monitor object is different?
Ex: This is an example but I'm not sure if it's a good one. I just want to know if it is possible to call a synchronized method or block by two or more threads simultaneously. Or always a synchronized method cannot be called by
public class SynchronizedExchanger {
protected Object object = null;
public synchronized void setObject(Object o) {
System.out.println("Do something, o = " + o);
this.object = o;
}
}
public class SynchronizedExchangerMainDemo {
public static void main(String[] args) {
SynchronizedExchanger exchanger = new SynchronizedExchanger();
SynchronizedExchanger exchanger1 = new SynchronizedExchanger();
Thread thread1 = new Thread(
new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
exchanger.setObject("" + i);
}
}
}
);
Thread thread2 = new Thread(
new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
exchanger1.setObject("" + i);
}
}
}
);
}
}