阻塞队列将等待元素出列多长时间?

问题描述:

我在我的程序中使用了阻塞队列实现。我想知道线程等待元素出队的时间。 我的客户投票回应,我的服务器线程提供消息。我的代码如下;阻塞队列将等待元素出列多长时间?

private BlockingQueue<Message> applicationResponses= new LinkedBlockingQueue<Message>(); 

客户端:

Message response = applicationResponses.take(); 

服务器:

applicationResponses.offer(message); 

将我的客户端线程等待下去吗?我想配置时间..(例如:1000毫秒)..是可能的吗?

是的,它会永远等待,直到你可以采取一个元素。如果你想有最长的等待时间,你应该使用轮询(时间,时间单位)。

Message response = applicationResponse.poll(1, TimeUnit.SECONDS); 

参见:http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/LinkedBlockingQueue.html#poll(long,%20java.util.concurrent.TimeUnit)

这两个选项来排队(报价)或出队(调查)从队列中的元素必须设置配置的超时选项。下面的方法javadoc:

/** 
* 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;