一、生产者消费者模式
1. 线程通信问题
2. 线程通信解决方式
(1)管程法
(2)信号灯法
3、生产者消费者代码
package com.dhu.thread.cooperation;
/**
* 协作模型:生产者消费者实现方式一:管程法
* 借助缓冲区
* @author zhou
*
*/
//生产者
class Productor extends Thread{
SynContainer container;
public Productor(SynContainer container) {
this.container = container;
}
@Override
public void run() {
for (int i = 1; i <= 30; i++) {
System.out.println("生产第" + i + "个面包");
container.push(new Bread(i));
}
}
}
//消费者
class Consumer extends Thread{
SynContainer container;
public Consumer(SynContainer container) {
this.container = container;
}
@Override
public void run() {
for (int i = 1; i <= 30; i++) {
System.out.println("消费者消费第" + container.pop().id + "个");
}
}
}
//缓冲区
class SynContainer{
private Bread[] list = new Bread[10];
int cnt = 0; //计数器
//生产面包
public synchronized void push(Bread bread) {
if(cnt == list.length) {
try {
this.wait(); //等待消费者消费,消费者通知生产阻塞解除
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list[cnt ++] = bread;
this.notifyAll();
}
//消费面包
public synchronized Bread pop() {
if(cnt == 0) {
try {
this.wait(); //线程阻塞,等待生产者通知消费才解除阻塞
} catch (InterruptedException e) {
e.printStackTrace();
}
}
cnt --;
Bread bread = list[cnt];
this.notify();
return bread;
}
}
//数据
class Bread{
int id;
public Bread(int id) {
this.id = id;
}
}
public class CoTest01 {
public static void main(String[] args) {
SynContainer c = new SynContainer();
new Productor(c).start();
new Consumer(c).start();
}
}