-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProducerConsumerTest.java
89 lines (81 loc) · 2.03 KB
/
ProducerConsumerTest.java
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
public class ProducerConsumerTest {
public static void main(String[] args) {
monitor c = new monitor();
Consumer c1 = new Consumer(c, 1);
Producer p1 = new Producer(c, 1);
Consumer c2 = new Consumer(c, 2);
Producer p2 = new Producer(c, 2);
System.out.print("\nConsumer 1 \n");
c1.start();
System.out.print("\nConsumer 2 \n");
c2.start();
System.out.print("\nProducer 1 \n");
p1.start();
System.out.print("\nProducer 2 \n");
p2.start();
}
}
class monitor {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
System.out.print("\nConsumer waiting\n");
}
catch (InterruptedException e) {
}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
System.out.print("\nProducer waiting\n");
}
catch (InterruptedException e) {
}
}
contents = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread {
private monitor monitor;
private int number;
public Consumer(monitor c, int number) {
monitor = c;
this.number = number;
}
public void run() {
// System.out.print("\nconsumer process being called\n");
int value = 0;
value = monitor.get();
System.out.println("Consumer #"
+ this.number
+ " got: " + value);
}
}
class Producer extends Thread {
private monitor monitor;
private int number;
public Producer(monitor c, int number) {
monitor = c;
this.number = number;
}
public void run() {
int num = (int)(Math.random() * 10);
//System.out.print("\n Calling producer\n");
monitor.put(num);
System.out.println("Producer #" + this.number
+ " put: " + num);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}