154.信号灯法

该博客通过一个Java实现的多线程例子展示了生产者消费者模型在实际场景中的应用,即影院的电影上线(生产者)与观众等待观影(消费者)。使用信号灯法(标志位)实现线程间的同步,确保资源(电影)的正确分配与使用。生产者演员类负责播放电影,消费者观众类负责观看。在danceHall类中,通过wait()和notify()方法协调线程状态,保证线程安全。

管程法的特点是,生产者和消费者之间是借助标志位达到线程同步的

写一个影院电影上线和观众等待电源上线的多线程例子

/*
 * 协作模式:生产者消费者实现方式2:信号灯法
 */
public class coTest02 {
	public static void main(String[] args) {
		danceHall dh = new danceHall();
		new player(dh).start();
		new auidence(dh).start();
	}
}

//生产者 演员
class player extends Thread{
	danceHall ah;
	public player(danceHall ah) {
		super();
		this.ah = ah;
	}
	public void run() {
		String[] str = new String[3];
		str[0] = "奇葩说";
		str[1] = "一人之下";
		str[2] = "权力的游戏";
		for(String st : str) {
			ah.play(st);
		}
	}
}
//消费者 观众
class auidence extends Thread{
	danceHall ah;

	public auidence(danceHall ah) {
		super();
		this.ah = ah;
	}
	public void run() {
		for(int i=0; i<3; ++i)
			ah.view();
	}
}
//同一个资源:影院
class danceHall{
	private String item;
	/*
	 * 信号灯
	 * T 演员表演,观众等待
	 * F 观众观看,演员等待
	 */
	boolean flag = true;
	
	//表演
	public synchronized void play(String it) {
		//F
		if(!flag) {
			try {
				this.wait();
			} catch (InterruptedException e) {
			}
		}
		//T
		System.out.println("表演了"+it);
		this.item = it;
		this.notify();
		this.flag = !this.flag;
	}
	//观看
	public synchronized void view() {
		//T
		if(flag) {
			try {
				this.wait();
			} catch (InterruptedException e) {
			}
		}
		//F
		System.out.println("观看了"+this.item);
		this.notify();
		this.flag = !this.flag;
	}
}

通过标志位,达到线程之间对资源请求操作的阻塞和唤醒切换,主要注意的地方就是当前线程操作完成后除了要唤醒其它线程之外还有更改标志位

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值