-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLab12.java
More file actions
84 lines (72 loc) · 1.39 KB
/
Lab12.java
File metadata and controls
84 lines (72 loc) · 1.39 KB
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
// Producer Consumer Problem
class Buffer {
int i, flag = 0;
synchronized void put(int x) {
try {
if (flag == 1)
wait();
} catch (Exception e) {
System.out.println(e);
}
i = x;
System.out.println("Produced " + i);
flag = 1;
notify();
}
synchronized void get() {
try {
if (flag == 0)
wait();
} catch (Exception e) {
System.out.println(e);
}
System.out.println("Consumed " + i);
flag = 0;
notify();
}
}
class Producer implements Runnable {
Buffer b;
Thread t;
Producer(Buffer b) {
this.b = b;
t = new Thread(this, "Producer");
t.start();
}
public void run() {
int i = 0;
while (true) {
b.put(i++);
}
}
}
class Consumer implements Runnable {
Buffer b;
Thread t;
Consumer(Buffer b) {
this.b = b;
t = new Thread(this, "Consumer");
t.start();
}
public void run() {
while (true) {
b.get();
}
}
}
public class Lab12 {
public static void main(String args[]) {
Buffer b = new Buffer();
new Producer(b);
new Consumer(b);
}
}
/*
* Output:
* Produced 0
* Consumed 0
* Produced 1
* Consumed 1
* Produced 2
* Consumed 2
*/