问题描述
在Java中,如果同步方法包含对非同步的调用,是否还有另一种方法可以同时访问非同步方法?基本上我要问的是同步方法中的所有内容都有锁(包括调用其他同步方法)?非常感谢
In Java, if a synchronized method contains a call to a non-synchronized, can another method still access the non-synchronized method at the same time? Basically what I'm asking is everything in the synchronized method have a lock on it (including calls to other synchronized methods)? Thanks so much
推荐答案
是和否。
如果你在 synchronized
方法中,然后调用其他线程的 synchronized
的其他方法被锁定。但是,其他线程对非同步方法的调用不已锁定 - 任何人都可以同时调用它们。
If you are in a synchronized
method, then calls to other methods that are also synchronized
by other threads are locked. However calls to non-synchronized methods by other threads are not locked -- anyone can call them at the same time.
public synchronized void someSynchronizedMethod() {
...
someNonSynchronizedMethod();
...
}
// anyone can call this method even if the someSynchronizedMethod() method has
// been called and the lock has been locked
public void someNonSynchronizedMethod() {
...
}
此外,如果你调用 someSynchronizedMethod()
但恰好在 someNonSynchronizedMethod()
方法中,你仍然持有锁。输入同步块时启用锁定,退出该方法时禁用锁定。你可以调用各种其他不同步的方法,但它们仍然会被锁定。
Also, if you call someSynchronizedMethod()
but happen to be within the someNonSynchronizedMethod()
method, you still hold the lock. The lock is enabled when you enter a synchronized block and is disabled when you exit that method. You can call all sorts of other unsynchronized methods and they will still be locked.
但你问的是两个不同的问题:
But you are asking two different things in your question:
是的。其他方法可以访问非同步方法。
Yes. Other methods can access non-synchronized methods.
呃,是的。对 synchronized 方法的其他调用将被锁定。但是非同步方法没有被锁定。
Uh, yes. Other calls to synchronized methods are locked. But non-synchronized methods are not locked.
另外,请记住,如果方法是 static
,那么锁是在 ClassLoader
中的 Class
对象上。
Also, remember that if the method is static
then the lock is on the Class
object in the ClassLoader
.
// this locks on the Class object in the ClassLoader
public static synchronized void someStaticMethod() {
如果方法是实例方法,则锁定在类的实例上。
If the method is an instance method then the lock is on the instance of the class.
// this locks on the instance object that contains the method
public synchronized void someInstanceMethod() {
在这两种情况下有2种不同的锁。
There are 2 different locks in those 2 cases.
最后,当你处理 synchronized
时实例方法,类的每个实例都是锁定的。这意味着两个线程可以使用不同的实例同时位于同一 synchronized
方法中。但是如果2个线程试图在同一个实例上对 synchronized
方法进行操作,则会阻塞,直到另一个退出该方法。
Lastly, when you are dealing with synchronized
instance methods, each instance of the class is what is locked. This means that two threads could be in the same synchronized
method at the same time with different instances. But if 2 threads try to operate on synchronized
methods on the same instance, one will block until the other one exits the method.
这篇关于如果synchronized方法调用另一个非同步方法,那么非同步方法是否存在锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!