java - java同步是如何工作的

标签 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/

相关文章:

java - 需要使用枚举

java.net.SocketException : Connection reset 异常

java - 如何使用 JSR-310 DateTimeFormatter 解析不区分大小写的字符串?

java - 使用 selenium Web Driver 中的 Robot 类上传功能

java - 从多个类的数组中的同一类中删除对象的更简洁的方法

java - 在多个层次依赖关系中模拟对象时是否有难闻的气味?

java - 线程中未调用 Run 方法

java - 如何获取嵌套类型内部结构的所有类型?

java - Gradle:通过版本分类器覆盖传递依赖

c# - Java 和 C# 中二进制文件的最佳编码解码