简体   繁体   中英

java monitor - queues

I have a java monitor, but i need some explanation:

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?

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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