2013-05-01 83 views
1

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

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

客户端:

Message response = applicationResponses.take(); 

服务器:

applicationResponses.offer(message); 

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

回答

1

这两个选项来排队(报价)或出队(调查)从队列中的元素必须设置配置的超时选项。下面的方法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;