0

I have 4 class - Producer, Consumer, Shop, Main.

Trying to calculate average waiting time which customers are in the queue for waiting to enter the store.

My run method in Producer -

public void run() {
  for (int i = 1; i < size; i++) {

     shop.put(i);
     System.out.println("Customer number "  + i + " has entered the store\n");
     enterStore = System.currentTimeMillis();
     try {
        Thread.sleep((int) (Math.random() * 1000));

     } catch (InterruptedException e) { }
  }
}

Part of my put method in Shop -

System.out.println("The store is full! Customer " + value + " is waiting in the queue.....\n");
        queueStart = System.currentTimeMillis();
        System.out.println("Customer joined queue at time : " + queueStart);

        wait();

And part of my Main -

double averageTime = (Shop.queueStart - Producer.enterStore)/20;
  System.out.println("Average time customer queued outside store = " + averageTime);

Everything else in my code is working fine - but the average prints a minus number so I've obviously gone wrong somewhere. I'm really new to java and just looking for some help!

Thanks!

  • Well, since you enter the store after joining the queue, you should probably reverse the order - `double averageTime = ( Producer.enterStore - Shop.queueStart)/20;` – Eran Apr 01 '14 at 19:43
  • This isn't related to your question, but using a Thread.sleep(int) is not the best way to solve the producer-consumer problem. Consider working with wait() and notify(), or, better, semaphores http://en.wikipedia.org/wiki/Semaphore_(programming) – Dylan Meeus Apr 01 '14 at 19:48

1 Answers1

0

The later the time, the higher the double value, therefore you need to switch the subtraction operands, so that you get

Producer.enterStore - Shop.queueStart
Warlord
  • 2,798
  • 16
  • 21