-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathProducerConsumerProblem.java
More file actions
86 lines (68 loc) · 1.82 KB
/
ProducerConsumerProblem.java
File metadata and controls
86 lines (68 loc) · 1.82 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
import java.util.*;
public class ProducerConsumerProblem{
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
System.out.print("\nInput the size of the buffer queue: ");
int buf = sc.nextInt();
int countingSemaphore = 0;
int binarySemaphore = -1;
boolean sleep = false;
System.out.println("Initializing....\n");
Thread.sleep(2000);
System.out.println("Starting simulation...\n");
Thread.sleep(1000);
for(int i=1;i<=20;i++){
double f = Math.random();
System.out.print("t = "+i+"\t");
//System.out.print(f+" ");
if(f>0.5){
f=1; //Produce
binarySemaphore = 1;
}
else {
f=0; //Consume
binarySemaphore = 0;
}
if(binarySemaphore == 0){
/*Code for consumer*/
if(countingSemaphore>0){
System.out.println("Consumer consuming resource...\n");
countingSemaphore--;
sleep = false;
}
else{
if(sleep==true) {
System.out.println("Consumer asleep....\n");
}
else{
System.out.println("No items in the queue. Consumer is sleeping....\n");
sleep = true;
Thread.sleep(500);
}
continue;
}
}
else{
/*Code for producer*/
if(countingSemaphore == buf){
if(sleep==true){
System.out.println("Producer asleep....\n");
}
else{
System.out.println("The queue is full! Producer is sleeping....\n");
sleep = true;
Thread.sleep(500);
}
continue;
}
else{
countingSemaphore++;
System.out.println("Producer producing resource...\n");
sleep = false;
}
}
Thread.sleep(500);
}
System.out.println("\n\nResources left in the queue: "+countingSemaphore);
}
}