生产者和消费者模型:管程法(缓冲区)
- 防止两者操作同一个对象,全都互相等待对方的情况
管程法:调用缓冲区内的方法
本质上就是我停止的时候召唤你,你停止时召唤我
- 实现消费者和生产者通信效果
- 涉及多线程的方法就加上synchronized锁
package com.li.changGe.multithreading.threadCommunication;
public class BufferDemo01 extends Thread{
public static void main(String[] args) {
Buffer buffer = new Buffer();
new Production(buffer).start();
new Consumption(buffer).start();
}
}
//生产者
class Production extends Thread{
private Buffer buffer;
public Production(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
buffer.production(new Chick(i));
System.out.println("生产了"+i+"只鸡");
}
}
}
//消费者
class Consumption extends Thread{
private Buffer buffer;
public Consumption(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
Chick chick = buffer.consumption();
System.out.println("吃掉了第"+chick.getId()+"只鸡");
}
}
}//Consumption
class Chick{
public Chick(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
private Integer id;
}
//缓冲区
class Buffer extends Thread{
private Chick[] chicks = new Chick[10];
private int count = 0;
/**
* 消费者默认一直不停取
* 没有了才停下
*/
public synchronized Chick consumption(){
if(count == 0){
//等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}//if
count--;
Chick result = chicks[count];
this.notifyAll();
return result;
}
/**
* 生产者放入鸡
*
* 默认一直不停生产
* 唤醒其他线程
*/
public synchronized void production(Chick chick){
if(count == chicks.length){
//等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}//if
chicks[count] = chick;
count++;
this.notifyAll();
}
}