第一种 管程法
就拿去麦当劳去吃炸鸡例子,你去麦当劳吃炸鸡,你就是消费者,麦当劳的大厨就是生产者,当你去前台买炸鸡的时候,前台就相等于一个缓冲区,如果前台有炸鸡你就拿走吃,如果前台没有鸡的话,前台通知大厨生产炸鸡,你就等待。后厨生产到一定的数量后,前台就会通知你来拿炸鸡,这是后厨等待反复循环
生产者
//生产者
class Productor extends Thread{
SynContainer container;
public Productor(SynContainer container){
this.container = container;
}
// 生产方法
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Chicken(i));//把生产的鸡放到容器中
System.out.println("生产了"+i+"只鸡");
}
}
}
消费者
/消费者
class Consumer extends Thread{
SynContainer container;
public Consumer(SynContainer container){
this.container = container;
}
// 消费方法
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了-->"+container.pop().id+"只鸡");
}
}
}
产品
//产品 鸡
class Chicken{
int id;//产品编号
public Chicken(int id) {
this.id = id;
}
}
缓冲区
//缓冲区
class SynContainer{
// 需要一个容器大小
Chicken[] chickens = new Chicken[10];
//容器计数器
int count = 0;
// 生产者放入产品
public synchronized void push(Chicken chicken){
//判断如果容器满了,就等待消费者消费
if (count == chickens.length-1){
//生产者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断如果没有满,就丢入产品
chickens[count] = chicken;
count++;
//可以通知消费者消费
this.notifyAll();
}
// 消费者消费产品
public synchronized Chicken pop(){
//判断能否消费
if (count == 0){
//消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
Chicken chicken = chickens[count];
//通知生产者生产
this.notifyAll();
return chicken;
}
}
第二种方法 信号灯法(通过flag标志位)
生产者 演员
//生产者 演员
class Player extends Thread{
TV tv;
public Player(TV tv){
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (i%2==0){
this.tv.play("天天向上节目播放中");
}else{
this.tv.play("广告播放中");
}
}
}
}
消费者 观众
//消费者 观众
class Watcher extends Thread{
TV tv;
public Watcher(TV tv){
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
tv.watch();
}
}
}
产品 节目
//产品 节目
class TV{
//演员表演的时候,观众等待 T
//观众观看的时候,演员等待 F
String voice;//表演的节目
boolean flag = true;
//表演
public synchronized void play(String voice){
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员了表演了:"+voice);
//通知观众观看
this.notifyAll();
this.voice = voice;
this.flag = !this.flag;
}
//观看
public synchronized void watch(){
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观众观看了:"+voice);
//通知演员表演
this.notifyAll();
this.flag = !this.flag;
}
}