forked from sPredictorX1708/Ultimate-Java-Resources
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProducerConsumer.java
More file actions
107 lines (103 loc) · 2.43 KB
/
ProducerConsumer.java
File metadata and controls
107 lines (103 loc) · 2.43 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import java.util.concurrent.Semaphore;
import java.util.* ;
//Qitem contains buffer and full and empty indicators
class Qitem {
int item,
n,
full,
empty;
int[] buffer;
Qitem(int n) {
this.n = n;
buffer = new int[n];
full = 0;
empty = n;
}
int x;
//Semaphore initialised
static Semaphore sem = new Semaphore(1);
Random random = new Random();
void get() {
while (full <= 0);
try {
sem.acquire();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
int rand = random.nextInt(n);
if (buffer[rand] == 1) {
buffer[rand] = 0;
full--;
empty++;
System.out.println("Consumer consumed at " + rand + ", Buffer = " + Arrays.toString(buffer));
}
sem.release();
}
void put() {
while (empty <= 0);
try {
sem.acquire();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
int rand = random.nextInt(n);
if (buffer[rand] == 0) {
buffer[rand] = 1;
empty--;
full++;
System.out.println("Producer produced at " + rand + ", Buffer = " + Arrays.toString(buffer));
}
sem.release();
}
}
//Producer Class
//Qitem produced
class Producer extends Thread {
Qitem q;
long start = System.currentTimeMillis();
long end;
long time;
Producer(Qitem q, long time) {
this.q = q;
this.time = time;
end = start + time;
}
public void run() {
while (System.currentTimeMillis() < end) {
q.put();
}
}
}
//Consumer Class
//Qitem is item consumed by consumer
class Consumer extends Thread {
Qitem q;
long start = System.currentTimeMillis();
long end;
long time;
Consumer(Qitem q, long time) {
this.q = q;
this.time = time;
end = start + time;
}
public void run() {
while (System.currentTimeMillis() < end) {
q.get();
}
}
}
//Producer Consumer Runner Class
public class ProducerConsumer {
public static void main(String args[]) {
Scanner sc = new Scanner(System. in );
System.out.print("Enter duration of programme in milliseconds:");
long time = sc.nextInt();
System.out.print("Enter buffer length:");
int n = sc.nextInt();
Qitem q = new Qitem(n);
Producer p = new Producer(q, time);
Consumer c = new Consumer(q, time);
p.start();
c.start();
}
}