package com.aflfte.cooperation;
/**
* 协作模式:生产者与销费者实现方式二:信号灯法
* 借助标志位实现
* @author jinhao
*
*/
public class CoTest02 {
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;
}
public void run() {
for(int i=0;i<20;i++) {
if(i%20==0) {
this.tv.play("奇葩说");
}else {
this.tv.play("太亏了,来瓶立白洗洗嘴!");
}
}
}
}
//消费者 观众
class Watcher extends Thread{
TV tv;
public Watcher(TV tv) {
this.tv=tv;
}
public void run(){
for(int i=0;i<20;i++) {
tv.watch();
}
}
}
//同一个资源 电视
class TV{
String voice;
//信号灯 true表示生产中消费者等待,false表示消费中生产者等待
boolean flag=true;
//生产
public synchronized void play(String voice) {
//生产等待
if(!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
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 自动生成的 catch 块
e.printStackTrace();
}
}
//消费
System.out.println("听到了"+voice);
//唤醒生产
this.notifyAll();
//换灯
this.flag=!this.flag;
}
}
« 任务调度:定时执行任务
|
协作模型:管程法»
|