管程法
package com.lzy.cooperation;
/**
* 协作模型:生产者消费者实现方式一:管程法
* 借助缓冲区
* @author Administration
*
*/
public class CoTest01 {
public static void main(String[] args) {
SynContainer container=new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
//生产者
class Productor extends Thread{
SynContainer container;
public Productor(SynContainer container) {
this.container= container;
}
@Override
public void run() {
//生产、
for(int i=0;i<100;i++) {
System.out.println("生产-->"+i+"个馒头");
container.push(new Steamedbun(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 SynContainer{
Steamedbun[] buns=new Steamedbun[10];//存储容器
int count=0;//计数器
public synchronized void push(Steamedbun bun) {
//何时能生产 容器存在空间
//不能生产 只有等待
if(count==buns.length) {
try {
this.wait();//线程阻塞 消费者通知生产接触
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//存在空间 可以生产
buns[count]=bun;
System.out.println(count);
count++;
System.out.println(count);
//存在数据了,可以通知消费了
this.notifyAll();
}
//获取 消费
public synchronized Steamedbun pop() {
//何时消费 容器中是否存在数据
//没有数据 只有等待
if(count==0) {
try {
this.wait();//线程阻塞 生产者通知消费解除
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//存在数据可以消费
count--;
Steamedbun bun=buns[count];
this.notifyAll();//存在空间了,可以唤醒对方生产了
return bun;
}
}
//馒头
class Steamedbun{
int id;
public Steamedbun(int id) {
this.id=id;
}
}
信号灯法
package com.lzy.cooperation;
/**
* 协作模型:生产者消费者实现方式二:信号灯法
* 借助标志位
* @author Administration
*
*/
public class CoTest03 {
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) {
super();
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{
String voice;
//信号灯
//T表示演员表演 观众等待
//F表示观众观看 演员等待
boolean flag=true;
//表演
public synchronized void play(String voice) {
//演员等待
if(!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//表演
System.out.println("表演了"+voice);
this.voice=voice;
//唤醒
this.notifyAll();
//切换标志
this.flag=!this.flag;
}
//观看
public synchronized void watch() {
//观众等待
if(flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//观看
System.out.println("听到了:"+voice);
//唤醒
this.notifyAll();
//切换标志
this.flag=!this.flag;
}
}