class A {
private synchronized f() {
...
...
}
private void g() {
...
...
}
}
If thread T1 is running f() which is synchronized, can thread t2 run g() which is not synchronized at the same point of time, while T1 is still running f()?
Q6) Can two threads call two different static synchronized methods of the same class? Ans) No. The static synchronized methods of the same class always block each other as only one lock per class exists.So no two static synchronized methods can execute at the same time.
In the same multithreaded process in a shared-memory multiprocessor environment, each thread in the process can run concurrently on a separate processor, resulting in parallel execution, which is true simultaneous execution.
Indeed, it is not possible! Hence, multiple threads will not able to run any number of synchronized methods on the same object simultaneously.
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.
Not on the same instance of A. The instance itself is the lock so two execute the two methods at the same time with two threads you would need two instances of A.
Yes. Both methods can execute at the same time on the same instance.
Only f()
is synchronized. A thread must acquire the monitor for this.f()
to execute f()
and only one monitor exists per instance.
g()
is not synchronized, no monitor locking is required to run the method, so any thread can execute g()
at any time.
"A synchronized method acquires a monitor (§17.1) before it executes."
http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.3.6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With