Reputation: 131
Is synchronized
keyword in methods prevents running concurrently or calling concurrently by multiple threads in one instance?
We have one object and some synchronized
methods and different threads.
I read that synchronized methods prevents multiple threads calling synchronized methods on one object, But How different threads can running synchronized
methods concurrently?
Thanks.
Upvotes: 1
Views: 491
Reputation: 5208
If you have a class that looks like this,
class C {
public synchronized void method1() { ... }
public synchronized void method2() { ... }
}
You can't have any two threads running method1
, or method2
, or any combination of the two concurrently.
When using synchronized methods, you're declaring that at most one thread may be running one of the synchronized methods, in any given instant.
If there are methods you would like to run concurrently, you'll probably need to look into managing multiple locks (synchronized blocks, instead of methods, using some monitor other than this
).
Maybe you should start with this lesson.
First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
Upvotes: 1
Reputation: 32458
We have one one object and some synchronized methods and different threads.
Synchronization on methods will use the current instance (this) as the lock, so, if there is only on object, multiple thread can't run those methods concurrently.
Is synchronized keyword in methods prevents running concurrently or calling concurrently by multiple threads in one instance?
Prevents running concurrently by multiple threads.
But How different threads can running synchronized methods concurrently?
No, They can't run concurrently.
Upvotes: 3