-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp7.java
75 lines (73 loc) · 1.82 KB
/
p7.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
import java.util.*;
class sharedBuffered{
LinkedList<Integer>buffer=new LinkedList<>();
int capacity;
sharedBuffered(int capacity){
this.capacity=capacity;
}
void produce(int item) throws InterruptedException{
synchronized(this)
{
if(buffer.size()==capacity){
wait();
}
buffer.add(item);
System.out.println("Producing item: "+item);
notifyAll();
}
}
int consume() throws InterruptedException{
synchronized(this){
if(buffer.isEmpty()){
wait();
}
int item = buffer.removeFirst();
System.out.println("Consuming item "+item);
notifyAll();
return item;
}
}
}
class Producer implements Runnable{
sharedBuffered sh;
Producer(sharedBuffered sh){
this.sh=sh;
}
public void run(){
for(int i=1;i<=5;i++){
try{
sh.produce(i);
Thread.sleep(1000);
}
catch(Exception e){
Thread.currentThread().interrupt();
}
}
}
}
class Consumer implements Runnable{
sharedBuffered sh;
Consumer(sharedBuffered sh){
this.sh=sh;
}
public void run(){
for(int i=1;i<=5;i++){
try{
sh.consume();
Thread.sleep(1000);
}
catch(Exception e){
Thread.currentThread().interrupt();
}
}
}
}
class p7{
public static void main(String args[]){
sharedBuffered sh=new sharedBuffered(5);
Thread t1=new Thread(new Producer(sh));
Thread t2=new Thread(new Consumer(sh));
t1.start();
t2.start();
}
}