001package horstmann.ch09_queue1; 002/** 003 An action that repeatedly removes a greeting from a queue. 004 */ 005public class Consumer implements Runnable 006{ 007 /** 008 Constructs the consumer object. 009 @param aQueue the queue from which to retrieve greetings 010 @param count the number of greetings to consume 011 */ 012 public Consumer(BoundedQueue<String> aQueue, int count) 013 { 014 queue = aQueue; 015 greetingCount = count; 016 } 017 018 public void run() 019 { 020 try 021 { 022 int i = 1; 023 while (i <= greetingCount) 024 { 025 if (!queue.isEmpty()) 026 { 027 String greeting = queue.remove(); 028 System.out.println(greeting); 029 i++; 030 } 031 Thread.sleep((int)(Math.random() * DELAY)); 032 } 033 } 034 catch (InterruptedException exception) 035 { 036 } 037 } 038 039 private BoundedQueue<String> queue; 040 private int greetingCount; 041 042 private static final int DELAY = 10; 043}