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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| import java.util.LinkedList;
public class Storage { private final int MAX_SIZE = 100;
private LinkedList<Object> list = new LinkedList<>();
public void produce(int num) { synchronized (list) { while (list.size() + num > MAX_SIZE) { System.out.println("【要生产的产品数量】:" + num + "\t【库存量】:" + list.size() + "\t暂时不能执行生产任务!"); try { list.wait(); } catch (InterruptedException e) { e.printStackTrace(); } }
for (int i = 1; i <= num; ++i) { list.add(new Object()); }
System.out.println("【已经生产产品数】:" + num + "\t【现仓储量为】:" + list.size());
list.notifyAll(); } }
public void consume(int num) { synchronized (list) { while (list.size() < num) { System.out.println("【要消费的产品数量】:" + num + "\t【库存量】:" + list.size() + "\t暂时不能执行生产任务!"); try { list.wait(); } catch (InterruptedException e) { e.printStackTrace(); } }
for (int i = 1; i <= num; ++i) { list.remove(); }
System.out.println("【已经消费产品数】:" + num + "\t【现仓储量为】:" + list.size());
list.notifyAll(); } }
public LinkedList<Object> getList() { return list; }
public void setList(LinkedList<Object> list) { this.list = list; }
public int getMAX_SIZE() { return MAX_SIZE; } }
|