管程法的特点是,生产者和消费者之间是借助标志位达到线程同步的
写一个影院电影上线和观众等待电源上线的多线程例子
/*
* 协作模式:生产者消费者实现方式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;
}
}
通过标志位,达到线程之间对资源请求操作的阻塞和唤醒切换,主要注意的地方就是当前线程操作完成后除了要唤醒其它线程之外还有更改标志位
该博客通过一个Java实现的多线程例子展示了生产者消费者模型在实际场景中的应用,即影院的电影上线(生产者)与观众等待观影(消费者)。使用信号灯法(标志位)实现线程间的同步,确保资源(电影)的正确分配与使用。生产者演员类负责播放电影,消费者观众类负责观看。在danceHall类中,通过wait()和notify()方法协调线程状态,保证线程安全。
19万+

被折叠的 条评论
为什么被折叠?



