基本上我想要的是一个大小为 1 的 BlockingQueue。我有一个“监听器”线程,它只是等待、阻塞直到将对象放入队列,然后检索它——还有一个“生产者”线程,它实际上将对象放入队列。

我可以使用一些同步块(synchronized block)和 BlockingQueue 实现来实现这一点,但这似乎有点矫枉过正。有没有更好、更简单的方法来做我想做的事?

示例界面:

public interface Wait<T> {
  /**
   * If "put" has never been called on this object, then this method will
   * block and wait until it has. Once "put" has been called with some T, this
   * method will return that T immediately.
   */
  public T get() throws InterruptedException;

  /**
   * @param object The object to return to callers of get(). If called more
   * than once, will throw an {@link IllegalStateException}.
   */
  public void put(T object);
}

最佳答案

你的意思是类似 SynchronousQueue 的东西?另一个有用的类是 Exchanger

关于大小为 1 的 Java 阻塞队列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/214661/

10-14 15:34
查看更多