-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSyncConditionalWithCondition.java
More file actions
66 lines (55 loc) · 1.84 KB
/
SyncConditionalWithCondition.java
File metadata and controls
66 lines (55 loc) · 1.84 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
// Producer-Consumer Problem
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class ProductionPlantWithCondition extends ProductionPlant {
Lock lock = new ReentrantLock();
Condition produceConditionalLock = lock.newCondition();
Condition consumeConditionalLock = lock.newCondition();
int product;
boolean isProductReady = false; // Semaphore - binary
void produce(int product) {
lock.lock();
try {
if (isProductReady) {
try {
produceConditionalLock.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.product = product;
System.out.println("Conditional Product Produced - " + this.product);
isProductReady = true;
consumeConditionalLock.signal();
} finally {
lock.unlock();
}
}
void consume() {
lock.lock();
try {
if (!isProductReady) {
try {
consumeConditionalLock.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Conditional Product Consumed - " + this.product);
isProductReady = false;
produceConditionalLock.signal();
} finally {
lock.unlock();
}
}
}
public class SyncConditionalWithCondition {
public static void main(String[] args) {
ProductionPlant productionPlant = new ProductionPlantWithCondition();
Thread p = new Producer("Producer", productionPlant);
Thread c = new Consumer("Consumer", productionPlant);
p.start();
c.start();
}
}