Question:
If i synchronized two methods on the same class, can they run simultaneously on the same object? for example:
class A {
public synchronized void methodA() {
//method A
}
public synchronized void methodB() {
// method B
}
}
I know that I can't run methodA()
twice on same object in two different threads. same thing in methodB()
.But can I run
methodB()
on different thread while methodA()
is still running? (same object)Answer:
Putting
@reference_1_stackoverflowsynchronized
on a method means the thread has to
acquire the lock on the object instance before entering that method, so
if you have two different methods marked synchronized the threads
entering them will be contending for the same lock, and once one thread
gets the lock all other threads are shut out of all methods that
synchronize on that same lock. So in order for the two methods to run
concurrently they would have to use different locks, like this:class A {
private final Object lockA = new Object();
private final Object lockB = new Object();
public void methodA() {
synchronized(lockA) {
//method A
}
}
public void methodB() {
synchronized(lockB) {
//method B
}
}
}
If i synchronized two methods on the same class, can they run simultaneously?
The
synchronized
keyword applies on object level, and only one thread can hold the lock of the object. @reference_2_stackoverflow
Do two synchronized methods execute simultaneously
@reference_3_stackoverflow
Java two synchronized methods in one instance
@reference_4_stackoverflow
Object locking private class members - best practice? (Java)
No comments:
Post a Comment