wait-notify模式的典型应用
它可以实现生产者-消费者模式
wait-notify模式的经典写法
生产者和消费者的逻辑都可以统一抽象成以下几个步骤:
step1:获得对象的锁;
step2:循环判断是否需要进行生产活动,如果不需要进行生产就调用wait方法,暂停当前线程;如果需要进行生产活动,进行对应的生产活动;
step3:通知等待线程
package com.zry.ProducerConsumer;
import static java.lang.Thread.sleep;
/**wait-notify模式的典型应用#
* 它可以实现生产者-消费者模式
*wait-notify模式的经典写法#
* 生产者和消费者的逻辑都可以统一抽象成以下几个步骤:
*
* step1:获得对象的锁;
* step2:循环判断是否需要进行生产活动,如果不需要进行生产就调用wait方法,暂停当前线程;如果需要进行生产活动,进行对应的生产活动;
* step3:通知等待线程
*
* @author zry
* @ClassName ProducerConsumer.java
*
* @createTime 2021年12月28日
*/
class AppleBox {
private int appleCount;
AppleBox(int appleCount) {
this.appleCount = appleCount;
}
public synchronized void putInto() {
while(appleCount >= 50) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String name = Thread.currentThread().getName();
System.out.println("[" + name + "] 放入了一个苹果 , 箱子里有[" + ++appleCount + "]个苹果" );
this.notifyAll();
}
public synchronized void takeAway() {
while(appleCount <= 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
String name = Thread.currentThread().getName();
System.out.println("[" + name + "] 吃掉了一个苹果 , 箱子剩有[" + --appleCount + "]个苹果" );
this.notifyAll();
}
}
class Producer implements Runnable{
private AppleBox appleBox;
public Producer(AppleBox appleBox){
this.appleBox=appleBox;
}
@Override
public void run() {
while(true){
appleBox.putInto();
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable{
private AppleBox appleBox;
public Consumer( AppleBox appleBox){
this.appleBox=appleBox;
}
@Override
public void run() {
while(true){
appleBox.takeAway();
try {
sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ProducerConsumer {
public static void main(String[] args) {
AppleBox box = new AppleBox(60);
new Thread(new Producer(box),"Producer-1").start();
new Thread(new Consumer(box),"Consumer-1").start();
new Thread(new Consumer(box),"Consumer-2").start();
}
}