public void GetDrink()
 {
     while (Thread.CurrentThread.IsAlive)
     {
         if (Monitor.TryEnter(DrinkBuffer))
         {
             while (DrinkBuffer.GetBufferCurrent() == 0)
             {
                 Console.WriteLine(Name + " is waiting for the machine to refill");
                 Monitor.Wait(DrinkBuffer);
             }
             for (int i = 0; i < DrinkBuffer.Drinks.Length; i++)
             {
                 if (DrinkBuffer.Drinks[i] != null)
                 {
                     Console.WriteLine(Name + " Took a " + DrinkBuffer.Drinks[i].DrinkName + " and drank it");
                     DrinkBuffer.Drinks[i] = null;
                     i = DrinkBuffer.Drinks.Length + 1;
                 }
             }
             Monitor.Pulse(DrinkBuffer);
             Monitor.Exit(DrinkBuffer);
         }
     }
 }
Example #2
0
        static void Main(string[] args)
        {
            DrinkBuffer drinkBuffer = new DrinkBuffer(new Drink[20]);
            DrinkBuffer sodaBuffer  = new DrinkBuffer(new Drink[10]);
            DrinkBuffer beerBuffer  = new DrinkBuffer(new Drink[10]);
            Producer    producer    = new Producer(drinkBuffer);
            Producer    producer2   = new Producer(drinkBuffer);
            Splitter    splitter    = new Splitter(drinkBuffer, beerBuffer, sodaBuffer);
            Consumer    consumer    = new Consumer(beerBuffer, "Lars");
            Consumer    consumer2   = new Consumer(sodaBuffer, "Bob");

            Thread producerThread  = new Thread(producer.ProduceDrink);
            Thread producerThread2 = new Thread(producer.ProduceDrink);
            Thread splitterThread  = new Thread(splitter.SplitDrinks);
            Thread consumerThread  = new Thread(consumer.GetDrink);
            Thread consumerThread2 = new Thread(consumer2.GetDrink);

            producerThread.Start();
            splitterThread.Start();
            consumerThread.Start();
            //consumerThread2.Start();
        }
 public Splitter(DrinkBuffer incomingBuffer, DrinkBuffer beerBuffer, DrinkBuffer sodaBuffer)
 {
     IncomingBuffer = incomingBuffer;
     BeerBuffer     = beerBuffer;
     SodaBuffer     = sodaBuffer;
 }
 public Producer(DrinkBuffer buffer)
 {
     Buffer = buffer;
 }
 public Consumer(DrinkBuffer drinkBuffer, string name)
 {
     DrinkBuffer = drinkBuffer;
     Name        = name;
 }