-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProducer_Consumer_Semaphore.java
64 lines (56 loc) · 1.26 KB
/
Producer_Consumer_Semaphore.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
import java.util.concurrent.Semaphore;
class Producer_Consumer {
int item;
static Semaphore sem_Consumer = new Semaphore(0);
static Semaphore sem_Producer = new Semaphore(1);
void get(){
try {
sem_Consumer.acquire();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Item consumed by Consumer : " + item);
sem_Producer.release();
}
void put(int item){
try {
sem_Producer.acquire();
}
catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.item = item;
System.out.println("Item produced by Producer : " + item);
sem_Consumer.release();
}
}
class Producer implements Runnable {
Producer_Consumer pc;
Producer(Producer_Consumer q){
this.pc = q;
new Thread(this, "Producer").start();
}
public void run(){
for (int i = 0; i < 15; i++)
pc.put(i);
}
}
class Consumer implements Runnable {
Producer_Consumer pc;
Consumer(Producer_Consumer q){
this.pc = q;
new Thread(this, "Consumer").start();
}
public void run(){
for (int i = 0; i < 15; i++)
pc.get();
}
}
class Producer_Consumer_2{
public static void main(String args[]){
Producer_Consumer pc = new Producer_Consumer();
new Consumer(pc);
new Producer(pc);
}
}