7

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

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

客户:

    Message response = applicationResponses.take();

服务器:

    applicationResponses.offer(message);

我的客户线程会永远等待吗?我想配置那个时间..(例如:1000ms)..这可能吗?

4

2 回答 2

11

是的,它将永远等待,直到您可以获取元素。如果你想有一个最大的等待时间,你应该使用 poll(time, TimeUnit) 。

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)

于 2013-05-01T06:09:24.717 回答
2

从队列中排队(提供)或出列(轮询)元素的选项都可以选择设置可配置的超时。下面的方法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;
于 2013-05-01T06:10:25.110 回答