我正在我的程序中使用阻塞队列实现。我想知道线程将等待一个元素出队多长时间。 我的客户通过民意调查回复,我的服务器线程提供了消息。 我的代码如下;
private BlockingQueue<Message> applicationResponses= new LinkedBlockingQueue<Message>();
客户端:
Message response = applicationResponses.take();
服务器:
applicationResponses.offer(message);
我的客户端线程会永远等待吗?我想配置那个时间..(例如:1000ms)..这可能吗?
答案 0 :(得分:9)
是的,它会永远等待,直到你可以拿一个元素。如果你想拥有最长等待时间,你应该使用poll(time,TimeUnit)。
Message response = applicationResponse.poll(1, TimeUnit.SECONDS);
答案 1 :(得分:1)
队列中的队列(提供)或队列(轮询)元素的选项都可以选择设置可配置的超时。方法javadocs如下:
/**
* Inserts the specified element into this queue, waiting up to the
* specified wait time if necessary for space to become available.
*
* @param e the element to add
* @param timeout how long to wait before giving up, in units of
* <tt>unit</tt>
* @param unit a <tt>TimeUnit</tt> determining how to interpret the
* <tt>timeout</tt> parameter
* @return <tt>true</tt> if successful, or <tt>false</tt> if
* the specified waiting time elapses before space is available
* @throws InterruptedException if interrupted while waiting
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this queue
* @throws NullPointerException if the specified element is null
* @throws IllegalArgumentException if some property of the specified
* element prevents it from being added to this queue
*/
boolean offer(E e, long timeout, TimeUnit unit)
throws InterruptedException;
/**
* Retrieves and removes the head of this queue, waiting up to the
* specified wait time if necessary for an element to become available.
*
* @param timeout how long to wait before giving up, in units of
* <tt>unit</tt>
* @param unit a <tt>TimeUnit</tt> determining how to interpret the
* <tt>timeout</tt> parameter
* @return the head of this queue, or <tt>null</tt> if the
* specified waiting time elapses before an element is available
* @throws InterruptedException if interrupted while waiting
*/
E poll(long timeout, TimeUnit unit)
throws InterruptedException;