💩 Yikes, this is hard

main
Alexis Drai 2 years ago
parent 2e523915f0
commit 32db15a67c

@ -2,12 +2,13 @@ public class Customer implements Runnable {
private final PastryShop shop; private final PastryShop shop;
public Customer(PastryShop shop) { public Customer(PastryShop shop) {
System.out.println("I'm hungry");
this.shop = shop; this.shop = shop;
} }
@Override @Override
public void run() { public void run() {
//TODO System.out.println("customer running...");
shop.get(); shop.get();
} }
} }

@ -4,9 +4,13 @@ public class Main {
Thread producer1 = new Thread(new PastryChef(shop)); Thread producer1 = new Thread(new PastryChef(shop));
Thread consumer1 = new Thread(new Customer(shop)); Thread consumer1 = new Thread(new Customer(shop));
/* Thread consumer2 = new Thread(new Customer(shop));
Thread consumer3 = new Thread(new Customer(shop));
producer1.start(); producer1.start();
consumer1.start(); consumer1.start();
*/ consumer2.start();
consumer3.start();
} }
} }

@ -2,12 +2,13 @@ public class PastryChef implements Runnable {
private final PastryShop shop; private final PastryShop shop;
public PastryChef(PastryShop shop) { public PastryChef(PastryShop shop) {
System.out.println("I'm a chef");
this.shop = shop; this.shop = shop;
} }
@Override @Override
public void run() { public void run() {
//TODO System.out.println("chef running...");
shop.put(new Pastry()); shop.put(new Pastry());
} }
} }

@ -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…
Cancel
Save