如果我在同一个类上同步了两个方法,它们能同时在同一个对象上运行吗?例如:
class A {
public synchronized void methodA() {
//method A
}
public synchronized void methodB() {
// method B
}
}
我知道我不能在两个不同的线程中对同一个对象运行methodA()两次。在methodB()中也是如此。
但我可以运行methodB()在不同的线程,而methodA()仍在运行?(同一对象)
从oracle文档链接
使方法同步有两个效果:
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.
Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads
这将回答您的问题:在同一个对象上,当第一个同步方法正在执行时,您不能调用第二个同步方法。
看看这个文档页,了解内在锁和锁的行为。
Two different Threads executing a common synchronized method on the single object, since the object is same, when one thread uses it with synchronized method, it will have to verify the lock, if the lock is enabled, this thread will go to wait state, if lock is disabled then it can access the object, while it will access it will enable the lock and will release the lock
only when it's execution is complete.
when the another threads arrives, it will verify the lock, since it is enabled it will wait till the first thread completes his execution and releases the lock put on the object, once the lock is released the second thread will gain access to the object and it will enable the lock until it's execution.
so the execution will not be not concurrent, both threads will execute one by one, when both the threads use the synchronized method on different objects, they will run concurrently.