生产者与消费者问题
- 管程法-利用缓冲区解决
- 信号灯法-利用标志位解决
管程法
package com.edgar.gaoji;
//测试:生产者与消费者模型-->利用缓冲区解决-管程法
public class TestPC {
public static void main(String[] args) {
SynContainer synContainer = new SynContainer();
new Productor(synContainer).start();
new Customer(synContainer).start();
}
}
//生产者
class Productor extends Thread{
SynContainer synContainer;
public Productor(SynContainer synContainer) {
this.synContainer = synContainer;
}
@Override
public void run() {
for (int i = 1; i <=100; i++) {
try {
synContainer.push(new Chicken(i));
System.out.println("生产了"+i+"只鸡");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//消费者
class Customer extends Thread{
SynContainer synContainer;
public Customer(SynContainer
synContainer) {
this.synContainer = synContainer;
}
@Override
public void run() {
for (int i = 1; i <=100; i++) {
try {
System.out.println("消费了-->"+synContainer.take().id+"只鸡");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//产品
class Chicken{
int id;
public Chicken(int id) {
this.id = id;
}
}
//缓冲区
class SynContainer {
//需要一个容器大小
Chicken[] chickens= new Chicken[10];
//容器计数器
int num=0;
//生产者放入产品
public synchronized void push(Chicken chicken) throws InterruptedException {
//如果容器满了,就需要等待消费
if(num==chickens.length){
wait();
}
//如果没有满,继续丢入产品
chickens[num]=chicken;
num++;
//唤醒消费者去消费
this.notifyAll();
}
//消费者消费产品
public synchronized Chicken take() throws InterruptedException {
//如果容器为空,等待生产
if(num==0){
wait();
}
//如果没有空,取出产品
num--;
Chicken chicken=chickens[num];
//唤醒生产者去生产
this.notifyAll();
return chicken;
}
}
信号灯法
package com.edgar.gaoji;
//测试:生产者与消费者模型-->利用标志位解决-信号灯法
public class TestPC2 {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}
//生产者-->演员
class Player extends Thread {
private TV tv;
public Player(TV tv){
this.tv=tv;
}
@Override
public void run() {
for (int i = 0; i < 24; i++) {
if(i%2==0){
tv.play("电视剧神话");
}else{
tv.play("广告");
}
}
}
}
//消费者-->观众
class Watcher extends Thread {
private TV tv;
public Watcher(TV tv){
this.tv=tv;
}
@Override
public void run() {
for (int i = 0; i < 24; i++) {
tv.watch();
}
}
}
//产品-->节目
class TV {
private String name;//表演的节目
//演员表演,观众等待T
//观众观看,演员等待F
boolean flag=true;//标志位
//表演
public synchronized void play(String name) {
if(!flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了"+name);
this.name=name;
this.notifyAll();
this.flag=!flag;
}
//观看
public synchronized void watch() {
if(flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观众观看了"+name);
this.notifyAll();
this.flag=!flag;
}
}