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