并发协作模型(生产者/消费者模式)-->信号灯法
default| 方法名 | 作用 |
|---|---|
| wait() | Object wait() 方法让当前线程进入等待状态。直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。 |
| wait(long timeout) | Object wait(long timeout) 方法让当前线程处于等待(阻塞)状态,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者超过参数 timeout 设置的超时时间。 |
| 如果 timeout 参数为 0,则不会超时,会一直进行等待,类似于 wait() 方法。 | |
| notify() | Object notify() 方法用于唤醒一个在此对象监视器上等待的线程。 |
| 如果所有的线程都在此对象上等待,那么只会选择一个线程,选择是任意性的,并在对实现做出决定时发生。 | |
| notifyAll() | Object notifyAll() 方法用于唤醒在该对象上等待的所有线程。优先级别高的线程有限调度。 |
| notifyAll() 方法跟 notify() 方法一样,区别在于 notifyAll() 方法唤醒在此对象监视器上等待的所有线程,notify() 方法是一个线程。 |
信号灯法类似于一个缓冲区很小的管程法
参考资料:
public class TestPc2 {
public static void main(String[] args) {
Tv tv = new Tv();
new Player(tv).start();
new Watcher(tv).start();
}
}
/**
* 产品-->节目
* 演员表演,观众等待
* 观众观看,演员等待
*/
class Tv {
/**
* 表演的节目
*/
String voice;
/**
* 标志位
*/
boolean flag = true;
public synchronized void play(String voice) {
// 观众观看,演员等待
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了" + voice);
// 通知观众观看
this.notifyAll();
this.voice = voice;
this.flag = !flag;
}
public synchronized void watch() {
// 若未表演,观众等待
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观众观看了" + this.voice);
// 通知演员表演
this.notifyAll();
this.flag = !flag;
}
}
/**
* 生产者,演员
*/
class Player extends Thread {
private Tv tv;
public Player(Tv tv) {
this.tv = tv;
}
@Override
public void run() {
// 生产100个产品
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
this.tv.play("舞蹈");
} else {
this.tv.play("广告");
}
}
}
}
/**
* 消费者,观众
*/
class Watcher extends Thread {
private Tv tv;
public Watcher(Tv tv) {
this.tv = tv;
}
@Override
public void run() {
// 消费100个产品
for (int i = 0; i < 10; i++) {
this.tv.watch();
}
}
}