java - notify()之后的锁获取顺序

标签 java multithreading

假设线程 T1 正在等待进入同步块(synchronized block),线程 T2 在同步块(synchronized block)内 wait(),并且线程 T3 在同步块(synchronized block)上调用 notify() block 的监视器。

T1有可能在T2继续之前进入区 block 吗?还是T2优先?

最佳答案

Is it possible for T1 to enter the block before T2 proceeds?

是的,这是可能的。 Object.wait(int) 的 javadoc没有指定已通知的线程优先。事实上,它指定应用正常调度规则。

"The thread T is then removed from the wait set for this object and re-enabled for thread scheduling. It then competes in the usual manner with other threads for the right to synchronize on the object ..."

<小时/>

这是您需要编写这样的条件变量代码的原因之一

  private boolean condition = ...
  private Object lock = new Object();  // mutex for 'condition'

  ...

  synchronize (lock) {
      while (!condition) {
           wait(lock);
           // It is UNSAFE to assume that 'condition' is true now.
      }
  }

关于java - notify()之后的锁获取顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32446393/

相关文章:

java - Spring CORS错误

java 8,List<Employee> 映射部门和地址列表

java - 我的 while 循环对于我的方法来说是否太快?

java - 在netty库中,我想知道如何根据cpu号创建多个线程?

java - 如何在 hibernate 过滤器中使用 session.commit?

java - Android 获取 EditText 中的值

java - 为什么ObjectMapper将Date类型改为Long

c++ - 在没有 c++11 的情况下使用 boost 标记线程退出的正确方法是什么

c# - 检查线程是否返回线程池

c++ - Cent OS 6.3 上 usleep 的 CPU 使用率高