-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathClient.java
More file actions
55 lines (49 loc) · 1.8 KB
/
Copy pathClient.java
File metadata and controls
55 lines (49 loc) · 1.8 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
import java.util.concurrent.TimeUnit;
/**
* Client is meant to be a producer or consumer. Each client has access to the
* DonutStorage does the respective action with donuts.
*/
public class Client {
public static final ClientOperation consume = (donutStorage, numberOfItems) -> {
int numberOfConsumedItems = 0;
for (int i = 0; i < numberOfItems; i++) {
try {
if (donutStorage.blockingQueue.poll(1, TimeUnit.SECONDS) != null) {
numberOfConsumedItems++;
}
} catch (InterruptedException ignored) {
}
}
return numberOfConsumedItems;
};
public static final ClientOperation produce = (donutStorage, numberOfItems) -> {
int numberOfProducedItems = 0;
for (int i = 0; i < numberOfItems; i++) {
try {
if (donutStorage.blockingQueue.offer(new Object(), 1, TimeUnit.SECONDS)) {
numberOfProducedItems++;
}
} catch (InterruptedException ignored) {
}
}
return numberOfProducedItems;
};
private final ClientOperation clientOperation;
private final DonutStorage donutStorage;
public Client(ClientOperation clientOperation, DonutStorage donutStorage) {
this.clientOperation = clientOperation;
this.donutStorage = donutStorage;
}
/**
*
* @param numberOfItems number that represents how to change the donutsNumber
* @return number that represents how the donutsNumber was changed
*/
public int operate(int numberOfItems) {
return clientOperation.operate(donutStorage, numberOfItems);
}
@FunctionalInterface
private interface ClientOperation {
int operate(DonutStorage donutStorage, int numberOfItems);
}
}