简体   繁体   English

无限阻塞队列Java

[英]Unbounded Blocking Queue Java

Requirement: Implement unbounded blocking queue ie thread calling get should block if no element present in queue. 要求:实现无限制的阻塞队列,即,如果队列中不存在任何元素,则调用get的线程应阻塞。

public class BlockingQueue<T> {

  private Queue<T> queue = new LinkedList<>();
  private Object monitor = new Object();

  /**
   * add element to queue
   */
  public void add(T element) {
    synchronized (monitor) {
      queue.add(element);
      monitor.notify();
    }
  }

  /**
   * Returns element if present in queue
   * otherwise calling thread blocks until an element is added to queue
   *
   * @return element from queue
   */
  public T get() throws InterruptedException {
    synchronized (monitor) {
      while (queue.isEmpty()) {
        monitor.wait();
      }
      return queue.poll();
    }
  }
}

Questions 问题
1. is implementation correct ? 1.实施正确吗?
2. invoking wait(); 2.调用wait(); moves thread from RUNNABLE to WAIT state 将线程从RUNNABLE移到WAIT状态
invoking notify(); 调用notify(); moves thread from WAIT to BLOCKED state 将线程从等待状态转移到阻塞状态
which action moves thread from BLOCKED to RUNNABLE state ? 哪个动作将线程从“已阻止”状态转换为“可运行”状态?

Is the implemntation correct? 暗示正确吗?

Yes

Just one remark : you may want to make the monitor field final . 只需提一句:您可能希望使monitor字段final

Which action moves thread from BLOCKED to RUNNABLE state ? 哪个动作将线程从BLOCKED变为RUNNABLE状态?

The action of a thread releasing the lock the BLOCKED thread is waiting for. 释放BLOCKED线程正在等待的锁的线程的动作。

Of course it could be that another thread acquires the lock on the monitor, and then this thread will remain BLOCKED until it gets a chance to acquire the lock on the monitor itself. 当然,可能是另一个线程获取了监视器上的锁,然后该线程将保持阻塞状态,直到有机会获取监视器本身上的锁为止。

For clarity, a call of wait() on a monitor causes the calling thread go into WAIT state, but it also causes the thread to release all its locks on monitors. 为了清楚起见,在监视器上调用wait()会使调用线程进入WAIT状态,但也会导致线程释放其在监视器上的所有锁。 When such a thread is notified, it becomes BLOCKED because it needs to reacquire all the locks on all the monitors it had before, before it can continue. 当通知了这样的线程时,该线程将变为“阻塞”,因为它需要重新获取其之前拥有的所有监视器上的所有锁,然后才能继续。 That is why it goes from WAIT to BLOCKED first. 这就是为什么它先从等待变为阻塞的原因。

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

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