parent
2e523915f0
commit
32db15a67c
@ -1,23 +1,53 @@
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.Arrays;
|
||||||
|
|
||||||
public class PastryShop {
|
public class PastryShop extends ArrayList<Pastry> {
|
||||||
private final List<Pastry> stock = new ArrayList<>();
|
private static final int MAX_STOCK_SIZE = 20;
|
||||||
|
|
||||||
int head = 0, tail = 0; // probably wrong
|
public synchronized void put(Pastry pastry) {
|
||||||
|
while (getStock() == MAX_STOCK_SIZE) {
|
||||||
|
try {
|
||||||
|
System.out.println(getStock() + " pastries, producer blocked");
|
||||||
|
this.wait();
|
||||||
|
} catch (InterruptedException ex) {
|
||||||
|
// TODO what else can we do here?
|
||||||
|
System.err.println(Arrays.toString(ex.getStackTrace()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while (getStock() < MAX_STOCK_SIZE) {
|
||||||
|
this.add(pastry);
|
||||||
|
System.out.println("A Pastry was put in the shop -- " + getStock() + " remaining");
|
||||||
|
|
||||||
public boolean put(Pastry pastry) {
|
this.notify();
|
||||||
//TODO
|
}
|
||||||
stock.add(tail, pastry);
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public Pastry get() {
|
public synchronized Pastry get() {
|
||||||
//TODO
|
while (getStock() == 0) {
|
||||||
return stock.get(head);
|
try {
|
||||||
|
System.out.println(getStock() + " pastries, consumer blocked");
|
||||||
|
this.wait();
|
||||||
|
} catch (InterruptedException ex) {
|
||||||
|
// TODO what else can we do here?
|
||||||
|
System.err.println(Arrays.toString(ex.getStackTrace()));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
Pastry res = this.get(0);
|
||||||
|
this.remove(res);
|
||||||
|
System.out.println("A Pastry was got from the shop -- " + getStock() + " remaining");
|
||||||
|
|
||||||
|
this.notify();
|
||||||
|
|
||||||
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
public int getStock() {
|
public int getStock() {
|
||||||
return stock.size();
|
return this.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized void prime() {
|
||||||
|
this.notify();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in new issue