这个模式是我们最熟悉的模式了,一边可劲的造,一边可劲的吃。


那么这个模式的核心是什么呢?我按从左往右放,你从右往左拿。莫要乱了顺序。就不能从左往右拿吗?其实也是可以的,哈哈,怎么拿都随你,但是不同方法的算法不同罢了。无所谓。
关键点就是满了就不能放了,空了就不能拿了。
我们明确一个条件:先进先出,就是先创建的先消费,以免放坏,我们用不同的符号来表示拿的和放的位置。
情景:幼儿园老师现场给小朋友们做蛋糕,烤好一个就往桌子的盘子里放一个,假设桌子总共可以放 5 个。小朋友5个,做面包的老师2个。老师大概2分钟做一个,小朋友大概3、5分钟吃一个.
首先我们需要创建这个神奇的桌子。
老师放蛋糕的时候,就不要考虑小朋友拿到了哪一个,只考虑,桌子上是否放满了,放满就等待,没放满就接着放,纯粹一点不是更简单吗。
小朋友拿蛋糕的也是纯粹一些,就看桌子上是否有蛋糕,有就拿,没有就等待。
public class Table {private int count;//蛋糕的总数//拿蛋糕 和 放蛋糕 就按顺序来 1 2 3String[] buffer;private int tail;//下次 放 的位置private int head;//下次 拿 的位置public Table(int count) {this.buffer = new String[count];this.count = count;this.tail = 0;this.head = 0;this.count = 0;}public synchronized void put(String take) throws InterruptedException {try {while (count >= buffer.length) {wait();}} catch (InterruptedException e) {e.printStackTrace();}buffer[tail] = take;tail = (tail + 1) % buffer.length;count++;notifyAll();System.out.println(Thread.currentThread().getName() + " put() " + take);}public synchronized String take() throws InterruptedException {try {while (count <= 0) {wait();}} catch (InterruptedException e) {e.printStackTrace();}String take = buffer[head];head = (head + 1) % buffer.length;count--;notifyAll();System.out.println(Thread.currentThread().getName() + " take() " + take);return take;}}
public class MakerThread extends Thread {private final Table table;private static int number = 0;public MakerThread(String name, Table table) {super(name);this.table = table;}@Overridepublic void run() {super.run();while (true) {try {Thread.sleep(2000);table.put(number++ + "");} catch (InterruptedException e) {e.printStackTrace();}}}}
public class EaterThread extends Thread {private final Table table;public EaterThread(String name, Table table) {super(name);this.table = table;}@Overridepublic void run() {super.run();while (true) {try {Thread.sleep(5000);table.take();} catch (InterruptedException e) {e.printStackTrace();}}}}
public class Main {public static void main(String[] args) {Table table = new Table(5);MakerThread makerThread1 = new MakerThread("MakerThread1", table);MakerThread makerThread2 = new MakerThread("MakerThread2", table);makerThread1.start();makerThread2.start();EaterThread eaterThread1 = new EaterThread("EaterThread1", table);EaterThread eaterThread2 = new EaterThread("EaterThread2", table);EaterThread eaterThread3 = new EaterThread("EaterThread3", table);EaterThread eaterThread4 = new EaterThread("EaterThread4", table);EaterThread eaterThread5 = new EaterThread("EaterThread5", table);eaterThread1.start();eaterThread2.start();eaterThread3.start();eaterThread4.start();eaterThread5.start();}}

