<分区>
如果类 A 有两个同步方法,比如 methodA 和 methodB。如果一个线程正在访问 methodA,另一个线程是否可以访问 methodB?按照我的理解,当访问methodA时,线程获得了对象的锁,其他线程不应该同时访问methodB。但这会大大降低性能,对吧?而且,我似乎习惯于阅读一篇文章,说另一个线程可以访问 methodB。哪一个是正确的?
标签 java
<分区>
如果类 A 有两个同步方法,比如 methodA 和 methodB。如果一个线程正在访问 methodA,另一个线程是否可以访问 methodB?按照我的理解,当访问methodA时,线程获得了对象的锁,其他线程不应该同时访问methodB。但这会大大降低性能,对吧?而且,我似乎习惯于阅读一篇文章,说另一个线程可以访问 methodB。哪一个是正确的?
最佳答案
If class A has two synchronized methods, say, methodA and methodB. If one thread is accessing methodA, can another thread access methodB? According to my understanding, when accessing methodA, the thread get lock of the object, the other thread shouldn't be able to access methodB at the same time.
没错;如果一个线程持有该对象的锁,则其他线程必须等待才能获得该锁。当然,只有当两个线程都在完全相同的对象上调用方法时才会出现这种情况。
But this will downgrade the performance a lot, right?
这可能会影响性能,但有时是必要的,例如防止两个线程同时修改相同的数据。
And, I seemed used to read one article that says the other thread can access methodB. Which one is correct?
第一个正确,第二个错误。
关于java - java同步是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15761205/