-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProducerConsumer.java
89 lines (84 loc) · 2.14 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
//This depicts a Producer Consumer Problem Solved without using threads, which means the user controls the processes.
package producerconsumer;
import java.util.Scanner;
class producer_consumer{
//semaphores
int x=1;
int e=5;
int f=0;
int wait(int x)
{
--x;
return x;
}
int signal(int x)
{
++x;
return x;
}
void producer()
{
x=wait(x);
f=signal(f);
e=wait(e);
System.out.println("Producer has produced");
x=signal(x);
}
void consumer()
{
x=wait(x);
f=wait(f);
e=signal(e);
System.out.println("Costumer has Consumed");
x=signal(x);
}
producer_consumer()
{
String c;
do
{
System.out.println("1.Producer 2.Consumer 3.Exit");
int ch;
Scanner s=new Scanner(System.in);
ch=s.nextInt();
switch(ch)
{
case 1:
{
if(x==1&&f!=5)
{
producer();
}
else
{
System.out.println("Producer Waiting...");
}
break;
}
case 2:
{
if(x==1&&e!=5)
{
consumer();
}
else
{
System.out.println("Consumer Waiting...");
}
break;
}
case 3:
{
System.exit(0);
}
}
System.out.println("Do you want to continue(y/n)");
c=s.next();
}while(c.equalsIgnoreCase("y"));
}
}
public class ProducerConsumer {
public static void main(String[] args) {
new producer_consumer();
}
}