简单的问题,但我没有多线程经验。 如果两个线程使用相同的同步方法(在 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/