如何知道另一个线程是否执行 SynchronousQueue 轮询?

How to know if another thread does SynchronousQueue poll?

我有一个非常模糊的用例,但本质上我需要知道另一个线程是否执行 SynchronousQueue poll(超时)并且我想插入项目并取消阻止它。

有什么简单的方法可以做到这一点吗?从我天真的阅读 javadoc 代码和代码来看,似乎没有,但我想我会检查 SOE。

如果你实现了这个逻辑,并且你的生产者线程每次发现有另一个线程阻塞在 poll 上时向队列添加值会怎样 - 在哪里保证你的生产者放入队列的值将是被那个线程消耗,而不是另一个?

建议修改你的设计。生产者——将值添加到队列的线程——应该对消费者一无所知。让你产生一个请求消费者。我的意思是定义另一个队列并使使 poll 提交的当前线程提交 request。您当前的生产者线程从该新队列中获取请求并满足请求。您可以按照在两个线程之间作为 中介者 的方式实现请求对象。

所以在解决了很多问题(自定义队列,单独的 volatile 变量来跟踪插入)之后,使用 offer 方法得到了非常简单的解决方案:

/**
 * Inserts the specified element into this queue, if another thread is
 * waiting to receive it.
 *
 * @param e the element to add
 * @return {@code true} if the element was added to this queue, else
 *         {@code false}
 * @throws NullPointerException if the specified element is null
 */
public boolean offer(E e) {
    if (e == null) throw new NullPointerException();
    return transferer.transfer(e, true, 0) != null;
}

如果我只是 if(offer(e)) ... else ... 这有助于解锁消费者(如果有的话)。