- @Override
- public void run() {
- // 消费
- for (int i = 1; i <= 100; i++) {
- System.out.println("消费 -->"+container.pop().id+"馒头");
- }
- }
- }
- // 缓冲区
- class SynContainer{
- Steamedbun[] buns = new Steamedbun[10];// 存储容器
- int count = 0;// 计数器
- // 存储 生产
- public synchronized void push(Steamedbun bun) {
- // 何时能生产 容器存在空间
- // 不能生产 只能等待 消费者通知生产才解除
- if (count == buns.length) {
- try {
- this.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- // 存在空间 可以生产
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- buns[count] = bun;
- count++;
- this.notifyAll();// 存在数据 可以通知消费
- }
- // 获取 消费
- public synchronized Steamedbun pop() {
- // 何时消费 容器中是否存在数据
- // 没有数据 只有等待
- if (count == 0) {
- try {
- this.wait();// 线程阻塞 生产者通知消费解除阻塞
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- // 存在数据可以消费
- count--;
- Steamedbun bun = buns[count];
- this.notifyAll();// 存在空间了, 可以唤醒对方生产了
- return bun;
- }
- }
- // 馒头
- class Steamedbun{
- int id;
来源: http://www.bubuko.com/infodetail-2932787.html