-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProducerConsumer.java
117 lines (100 loc) · 3.25 KB
/
ProducerConsumer.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import java.util.Scanner;
class WorkProcedure{
public static int N;
public static int mutex;
public static int empty;
public static int full;
static int[] buffer;
static int[] user;
static int index = 0;
public WorkProcedure(int n){
N = n;
mutex = 1;
empty = N;
full = 0;
buffer = new int[n+1];
user = new int[n+1];
}
public static class Consumer implements Runnable{
public void run(){
while (true){
//wait(full)
while (full<=0){
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
full--;
while (mutex<=0){
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
mutex--;
//consume item
System.out.println("Consumer: "+user[full]+ ", Consumed Data: "+buffer[full]+ " from the buffer");
index--;
//signal(mutex)
mutex++;
//signal(empty)
empty++;
}
}
}
public static class Producer implements Runnable{
Scanner sc = new Scanner(System.in);
public void run(){
while (true){
//wait mutex
while (empty<=0) {
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
empty--;
//wait mutex
while (mutex<=0){
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
mutex--;
//produced item
System.out.print("Enter the name of Producer : ");
int no = sc.nextInt();
System.out.print("Enter the data : ");
int data = sc.nextInt();
buffer[index] = data;
user[index] = no;
index++;
System.out.println("Empty Space: "+(N-index) + " and Full Space: "+index);
//signal(mutex);
mutex++;
//signal(full);
full++;
}
}
}
}
public class ProducerConsumer {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of buffer : ");
int n = sc.nextInt();
WorkProcedure q = new WorkProcedure(n);
WorkProcedure.Producer producer = new WorkProcedure.Producer();
WorkProcedure.Consumer consumer = new WorkProcedure.Consumer();
Thread t1 = new Thread(producer);
t1.start();
Thread t2 = new Thread(consumer);
t2.start();
}
}