简体   繁体   English

java监视器-队列

[英]java monitor - queues

I have a java monitor, but i need some explanation:我有一个 java 监视器,但我需要一些解释:

class Test
{
  private int data;
  private boolean full = false;

  public synchronized int receive() {
    while (!full) wait();
    full = false;
    return data;
  }

  public synchronized void send(int value) {
    data = value;
    full = true;
    notify();
  }
}

I know, that just one running process can be inside the monitor, so I don't understand following things:我知道,监视器内只能有一个正在运行的进程,所以我不明白以下几点:

  • What exactly is the monitor?监视器究竟是什么? Whole the class or both synchronized methods?整个类还是两个同步方法?
  • How many queues of waiting threads are there?有多少个等待线程队列? Just one for whole class or one for each sync methods?整个班级只有一个还是每个同步方法一个?
  • If the monitor is whole class, how can be recognized as a monitor by Java if there is no monitor-like keyword on the definition of the class?如果监视器是整个类,如果在类的定义中没有类似监视器的关键字,Java如何将其识别为监视器?

In the case of the code you posted, since the methods are not static methods, the monitor is associated with the object, not the class: there is one such monitor for each instance of the class.在您发布的代码的情况下,由于方法不是静态方法,因此监视器与对象相关联,而不是与类相关联:类的每个实例都有一个这样的监视器。

There is one queue of waiting threads for each instance of this class.此类的每个实例都有一个等待线程队列。 The queue applies to both the synchronized methods, so if one thread is executing one of those methods, no other thread can execute either of those methods.队列适用于这两种同步方法,因此如果一个线程正在执行其中一种方法,则其他线程无法执行其中任何一种方法。

Every object and every class in Java has its own built in monitor. Java 中的每个对象和每个类都有自己的内置监视器。 The object monitors apply to nonstatic methods, and the class monitors apply to static methods.对象监视器适用于非静态方法,类监视器适用于静态方法。 The monitors are part of the language definition, and do not have to be explicitly declared or defined.监视器是语言定义的一部分,不必显式声明或定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM