场景介绍
- 现有一个肯德基餐厅,厨师负责生产出汉堡,顾客想要吃掉汉堡。
- 有固定的五个仓位,每个仓位可以放置一个汉堡。
- 当仓位满了之后厨师无法继续烹饪汉堡,只能等待顾客用膳。
- 当仓位中都没有汉堡的情况下,顾客无汉堡可吃,只能等待厨师烹饪
以上场景便是经典的生产者消费者案例,在《计算机操作系统》这门课中会有所涉及,该场景涉及线程的同步问题。
图解
代码实现
package com.design;
public class TestDemo {
public static void main(String[] args) {
KFC kfc = new KFC();
Thread custer = new Thread(new Custmer(kfc));
Thread cooker = new Thread(new Cooker(kfc));
custer.start();
cooker.start();
}
}
class KFC{
Hanberger[] box = new Hanberger[5];
int count = 0;
synchronized void push(Hanberger hanberger) {
if (count >= 4) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
box[count] = hanberger;
System.out.println(count+"号仓位生产出新的汉堡");
count++;
this.notifyAll();
}
}
synchronized void take()
{
if(count<=0)
{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
System.out.println(count+"号仓位的汉堡被吃掉");
count--;
this.notifyAll();
}
}
}
class Cooker implements Runnable
{
KFC kfc;
public Cooker(KFC kfc) {
this.kfc = kfc;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
kfc.push(new Hanberger(i));
}
}
}
class Custmer implements Runnable
{
KFC kfc;
public Custmer(KFC kfc) {
this.kfc = kfc;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
kfc.take();
}
}
}
class Hanberger {
int index;
public Hanberger(int i) {
this.index = i;
}
}
以上便实现了生产者消费者模式。能解决供不应求和供过于求,也能保证程序不出现死锁。
notifyall与wait方法
- notifyall与wait方法均直接继承于Object类
- 两方法必须在synchronized方法中调用