01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package horstmann.ch09_queue1;
/**
   An action that repeatedly removes a greeting from a queue.
 */
public class Consumer implements Runnable
{
  /**
      Constructs the consumer object.
      @param aQueue the queue from which to retrieve greetings
      @param count the number of greetings to consume
   */
  public Consumer(BoundedQueue<String> aQueue, int count)
  {
    queue = aQueue;
    greetingCount = count;
  }

  public void run()
  {
    try
    {
      int i = 1;
      while (i <= greetingCount)
      {
        if (!queue.isEmpty())
        {
          String greeting = queue.remove();
          System.out.println(greeting);
          i++;
        }
        Thread.sleep((int)(Math.random() * DELAY));
      }
    }
    catch (InterruptedException exception)
    {
    }
  }

  private BoundedQueue<String> queue;
  private int greetingCount;

  private static final int DELAY = 10;
}