-
Notifications
You must be signed in to change notification settings - Fork 0
/
qb154.java
85 lines (70 loc) · 1.82 KB
/
qb154.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
// Producer-Consumer Problem using wait & notify
/*
Write a complete multi-threaded program to meet following requirements:
-Two threads of same type are to be instantiated in the method main.
-Each thread acts as a producer as well as a consumer.
-A shared buffer can store only one integer information along with the source &
destination of the information at a time.
-The information produced is to be consumed by appropriate consumer.
-Both producers produce information for both consumers.
*/
class procon {
boolean status = false;
int data;
synchronized void produce(int n) {
if (status) {
System.out.println("Producer Waiting..");
try {
wait();
} catch (Exception e) {
}
}
data = n;
System.out.println("Produces: " + data);
status = true;
notify();
}
synchronized void consume() {
if (!status) {
System.out.println("Consumer Waiting..");
try {
wait();
} catch (Exception e) {
}
}
System.out.println("Consume: " + data);
status = false;
notify();
}
}
class Producer extends Thread {
procon pc;
public Producer(procon pc) {
this.pc = pc;
}
public void run() {
for (int i = 1; i <= 5; i++) {
pc.produce(i);
}
}
}
class Consumer extends Thread {
procon pc;
public Consumer(procon pc) {
this.pc = pc;
}
public void run() {
for (int i = 1; i <= 5; i++) {
pc.consume();
}
}
}
class solution {
public static void main(String[] args) {
procon pc = new procon();
Producer p = new Producer(pc);
Consumer c = new Consumer(pc);
p.start();
c.start();
}
}