有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中的多线程访问同步方法

这个问题很简单,但我对多线程没有经验。 如果两个线程使用相同的synchronized方法(在Java中),而第一个线程在给定时间无法访问该方法(因为第二个线程正在使用该方法),那么第一个线程是等待(冻结)一段时间,然后再次尝试访问它,还是干脆放弃,根本不访问它


共 (1) 个答案

  1. # 1 楼答案

    第一个方法阻塞并等待,直到它可以使用该方法,如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不能保证线程在释放锁后能够获取锁的顺序