并發(fā)協(xié)作之信號(hào)燈的代碼
/*
?* 實(shí)現(xiàn)生產(chǎn)者和消費(fèi)者模式的信號(hào)燈法
?* 借助標(biāo)志位
?*/
public class CoTest02 {
?? ?public static void main(String[] args) {
?? ??? ?Tv tv=new Tv();
?? ??? ?new Player(tv).start();
?? ??? ?new Watcher(tv).start();
?? ?}
}
//生產(chǎn)者? 演員
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) {
?? ??? ??? ??? ?this.tv.play("奇葩說(shuō)");
?? ??? ??? ?} else {
?? ??? ??? ??? ?this.tv.play("我是余得水");
?? ??? ??? ?}
?? ??? ?}
?? ?}
}
//消費(fèi)者? 觀眾
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();
?? ??? ?}
?? ?}
}
//同一個(gè)資源? 電視
class Tv {
?? ?String voice;
?? ?// 信號(hào)燈
?? ?// 為真表示演員表演觀眾等待
?? ?// 為假表示觀眾觀看演員等待
?? ?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();
?? ??? ?// 切換標(biāo)志
?? ??? ?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("聽(tīng)到了:" + voice);
?? ??? ?// 喚醒
?? ??? ?this.notifyAll();
?? ??? ?// 切換標(biāo)志
?? ??? ?this.flag = !this.flag;
?? ?}
}
標(biāo)簽: