为什么 java TransferQueue 在 "put()" 之后不能 "transfer()"?
Why java TransferQueue cannot "transfer()" after "put()"?
我有一个非常简单的代码片段:
public static void main(String [] args) throws InterruptedException {
TransferQueue<Integer> transferQueue = new LinkedTransferQueue<>();
System.out.println("Step1");
transferQueue.put(2);
System.out.println("Step2");
transferQueue.transfer(2);
System.out.println("Step3");
}
运行 这个程序,它打印:
Step1
Step2
然后挂在那里。那么为什么 "transfer()" 功能不起作用?
transfer(e)
方法的 javadoc 对此进行了解释。
More precisely, transfers the specified element immediately if there exists a consumer already waiting to receive it (in take()
or timed poll), else inserts the specified element at the tail of this queue and waits until the element is received by a consumer.
添加了重点!
在您的示例中,没有消费者接收元素,因此 transfer(2)
调用永远阻塞。
(这与前面的 put(2)
调用无关。)
我有一个非常简单的代码片段:
public static void main(String [] args) throws InterruptedException {
TransferQueue<Integer> transferQueue = new LinkedTransferQueue<>();
System.out.println("Step1");
transferQueue.put(2);
System.out.println("Step2");
transferQueue.transfer(2);
System.out.println("Step3");
}
运行 这个程序,它打印:
Step1
Step2
然后挂在那里。那么为什么 "transfer()" 功能不起作用?
transfer(e)
方法的 javadoc 对此进行了解释。
More precisely, transfers the specified element immediately if there exists a consumer already waiting to receive it (in
take()
or timed poll), else inserts the specified element at the tail of this queue and waits until the element is received by a consumer.
添加了重点!
在您的示例中,没有消费者接收元素,因此 transfer(2)
调用永远阻塞。
(这与前面的 put(2)
调用无关。)