gpt4 book ai didi

java - 访问java中的同步方法

转载 作者:行者123 更新时间:2023-12-01 22:22:55 25 4
gpt4 key购买 nike

简单的问题,但我没有多线程经验。如果两个线程使用相同的同步方法(在 Java 中),并且第一个线程无法在给定时间访问该方法(因为第二个线程正在使用该方法),那么第一个线程是否会等待(卡住)一段时间然后尝试再次访问它,或者它只是放弃并且根本不访问它?

最佳答案

第一个方法会阻塞并等待,直到它可以使用该方法为止,根据 doc

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.

我不是 100% 确定我是否没记错,但如果我没记错的话,JVM 不会对线程在释放锁后获取锁的顺序提供任何保证。

关于java - 访问java中的同步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29369207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com