wait\notify
![]()
管程法
package Thread.Demo10;
/**
* 等待\唤醒,wait\notify
* 消费者生产者模型--》利用缓冲区解决问题:管程法
* @author liu
*/
//生产者,消费者,产品,缓冲区
public class ProductorModem {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
//生产者
class Productor extends Thread {
SynContainer container;
public Productor(SynContainer container) {
this.container = container;
}
@Override
public void run() {
//生产了i只鸡
for (int i = 0; i < 100; i++) {
container.push(new Chickden(i));
System.out.println("生产了" + i + "只鸡");
}
}
}
//消费者
class Consumer extends Thread {
SynContainer container;
public Consumer(SynContainer container) {
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了--》" + container.pop().id + "只鸡");
}
}
}
//产品
class Chickden {
int id;//产品编号
public Chickden(int id) {
this.id = id;
}
}
//缓冲区
class SynContainer {
//需要一个容器大小
Chickden[] chickdens = new Chickden[10];
//容器计数器
int count = 0;
//生产者放入产品
public synchronized void push(Chickden chickden) {
//如果容器满了,就需要等待消费
if (count == chickdens.length) {
//通知消费者消费,生产者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没满,我们需要继续丢入产品
chickdens[count] = chickden;
count++;
//通知消费者消费
this.notifyAll();
}
//消费者消费
public synchronized Chickden pop() {
//判断能否消费
if (count == 0) {
//等待消费者生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
Chickden chickden = chickdens[count];
//吃完了,通知生产者生产
this.notifyAll();
return chickden;
}
}
信号灯法
package Thread.Demo10;
public class xinhaodengfa {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}
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("快乐大本营");
} else {
this.tv.play("西游记");
}
}
}
}
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();
}
}
}
class TV {
String voice;
boolean flag = true;
//演员表演,观众等待 T
public synchronized void play(String voice) {
if (!flag) {
this.voice = voice;
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演:" + voice);
this.notifyAll();
this.flag = !this.flag;
}
//观众看,演员等待 F
public synchronized void watch() {
if (flag) {
this.voice = voice;
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观众看:" + voice);
this.notifyAll();
this.flag = !this.flag;
}
}