管程法的特点是,生产者和消费者之间是借助标志位达到线程同步的
写一个影院电影上线和观众等待电源上线的多线程例子
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
;
boolean flag
= true;
public synchronized void play(String it
) {
if(!flag
) {
try {
this.wait();
} catch (InterruptedException e
) {
}
}
System
.out
.println("表演了"+it
);
this.item
= it
;
this.notify();
this.flag
= !this.flag
;
}
public synchronized void view() {
if(flag
) {
try {
this.wait();
} catch (InterruptedException e
) {
}
}
System
.out
.println("观看了"+this.item
);
this.notify();
this.flag
= !this.flag
;
}
}
通过标志位,达到线程之间对资源请求操作的阻塞和唤醒切换,主要注意的地方就是当前线程操作完成后除了要唤醒其它线程之外还有更改标志位
转载请注明原文地址:https://blackberry.8miu.com/read-11576.html