-
Notifications
You must be signed in to change notification settings - Fork 2
/
SPC.java
85 lines (80 loc) · 1.33 KB
/
SPC.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
/**
* @author Kireet
*
// solution to producer consumer problem
*/
class Shop
{
boolean item_present=false;
int item;
synchronized public void produce(int x)
{
if(item_present)
{
try {
System.out.println("Producer will wait for the consumer to consume...");
wait();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
item=x;
System.out.println(item +" has been produced...");
item_present=true;
notify();
}
synchronized public void consume()
{
if(!item_present)
{
try {
System.out.println("Consumer is waiting for the producer to produce...");
wait();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println(item +" consumed by consumer...");
item_present=false;
notify();
}
}
class Producer extends Thread
{
Shop s;
public void run()
{
for(int i=1;i<=10;i++)
s.produce(i);
}
Producer(Shop s)
{
this.s=s;
}
}
class Consumer extends Thread
{
Shop s;
public void run()
{
for(int i=1;i<=10;i++)
s.consume();
}
Consumer(Shop s)
{
this.s=s;
}
}
public class SPC {
public static void main(String[] args) {
Shop so= new Shop();
Producer pr= new Producer(so);
Consumer cr=new Consumer(so);
pr.start();
cr.start();
}
}