生产者/消费者问题
1.管程法
package com.zy.demo03;
public class TestPC {
public static void main(String[] args) {
SynContainer synContainer = new SynContainer();
new Productor(synContainer).start();
new Consumer(synContainer).start();
}
}
//生产者
class Productor extends Thread{
SynContainer container;
public Productor(SynContainer container){
this.container = container;
}
@Override
public void run(){
for (int i = 1; i <= 100; i++) {
System.out.println("生产了第"+i+"只鸡。");
try {
container.push(new Chicken(i));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//消费者
class Consumer extends Thread{
SynContainer container;
public Consumer(SynContainer container){
this.container = container;
}
@Override
public void run(){
for (int i = 1; i <= 100; i++) {
try {
System.out.println("消费了第"+container.pop()+"只鸡。");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//货物鸡
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) throws InterruptedException {
//如果容器满了,需要消费者来消费
if(count == chickens.length)
{
this.wait();
}
//如果容器没满,需要生产者放入
chickens[count] = chicken;
count++;
//有鸡了,可以通知消费者消费
this.notifyAll();
}
//创建消费者消费
public synchronized int pop() throws InterruptedException {
//如果容器为空,等待
if(count == 0)
{
this.wait();
}
//如果容器有鸡
count--;
Chicken chicken = chickens[count];
//消费后,提醒生产者生产
this.notifyAll();
return chicken.id;
}
}
2.信号灯法
package com.zy.demo03;
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{
Tv tv;
public Player(Tv tv)
{
this.tv = tv;
}
@Override
public void run(){
for (int i = 0; i < 20; i++) {
if( i%2 == 0)
{
try {
this.tv.play("电视剧");
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
try {
this.tv.play("广告播放中...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
//观众
class Watcher extends Thread{
Tv tv;
public Watcher(Tv tv)
{
this.tv = tv;
}
@Override
public void run(){
for (int i = 0; i < 20; i++) {
try {
tv.watch();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//节目
class Tv{
//演员录制,观众等待
//观众观看,演员等待
String vioce;//节目名
Boolean flag = true;//信号标识
//表演
public synchronized void play(String vioce) throws InterruptedException {
if(!flag)
{
this.wait();
}
System.out.println("演员表演录制了:"+vioce);
//通知观众观看
this.notifyAll();
//节目名变化
this.vioce = vioce;
//信号变化
this.flag = !this.flag;
}
//观看
public synchronized void watch() throws InterruptedException {
if(flag)
{
this.wait();
}
System.out.println("观众们观看:"+ vioce);
//看完后通知演员录制
this.notifyAll();
//信号变化
this.flag = !this.flag;
}
}