summaryrefslogtreecommitdiff
path: root/java/tests/Concurrency/Condition/Consumer.java
blob: de9c4061110ffd520d0bb9c5445b2e970251c767 (plain)
1
2
3
4
5
6
7
8
9
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//File: Consumer.java
//Seth Widoff 8/8/96
//This class attempts at random intervals to dequeue random elements
//from a queue. If the queue is empty the thread waits until an element
//has been enqueued and another thread has invoked the notify() method.

package tests.Concurrency.Condition;

import ACE.ASX.TimeValue;
import java.util.Random;

public class Consumer implements Runnable
{
  //Maximum pause between dequeues (in milliseconds)
  private static final int MAX_PAUSE = 1000;

  private SimpleMessageQueue queue_;
  private boolean stop_requested_ = false;
  private String name_;
  private int iterations_;
  private TimeValue timeout_;
  
  public Consumer(String name, 
		  SimpleMessageQueue queue, 
		  int iterations,
		  TimeValue timeout)
  {
    name_ = "Consumer " + name;
    queue_ = queue;
    iterations_ = iterations;
    timeout_ = timeout;
  }

  public void run()
  {
    //Set the random number generator seed to the current time in
    //milliseconds.

    Random random = new Random(System.currentTimeMillis());
    Integer element;

    for (int i = 0; i < iterations_; )
      {
	try
	  {
	    element = (Integer)queue_.dequeue(timeout_);
	    if (element != null)
	      {
		
		System.out.print("Consumer::run() " + name_ + " dequeued " + element.toString());
		System.out.println(" Queue size: " + queue_.size());
		
		Thread.sleep(random.nextLong() % MAX_PAUSE);
	      }
	    else
	      {
		System.out.println ("Null");
	      }
	    i++;
	  }
	catch(Exception excp)
	  {
	    System.out.print ("Consumer::run() Exception: ");
	    System.out.println(excp);
	  }
      }
  }

  public void requestStop()
  {
    stop_requested_ = true;
  }
}