package com.atguigu.bigdata.juc;
import java.util.concurrent.TimeUnit;
/**
* @auth tianmin
* @date 2020-03-02 - 17:04
* @nodes 生产者消费者模型
* 1.实现生产者、消费者交替
*
* 总结:
* 1.高内聚,低耦合,线程操作资源类.
* 2.判断条件---->业务逻辑---->通知
* 3.防止虚假唤醒
*/
public class ProductConsume {
public static void main(String[] args) {
AirCondition air = new AirCondition();
// 启动2个线程,一个生产,一个消费
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
//TimeUnit.MILLISECONDS.sleep(100);
air.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"生产者1").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
//TimeUnit.MILLISECONDS.sleep(300);
air.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"生产者2").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
//TimeUnit.MILLISECONDS.sleep(200);
air.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"消费者1").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
//TimeUnit.MILLISECONDS.sleep(400);
air.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"消费者2").start();
}
}
class AirCondition{
private int number = 0;
//生产
public synchronized void increment() throws InterruptedException {
// 1 判断
// 1.1 线程间通信,不能用if 只能用while
while (number != 0){
//线程等待
this.wait();
}
// 2 业务逻辑
number++;
System.out.println("生产到了:" + number);
// 3 通知
this.notifyAll();
}
//消费
public synchronized void decrement() throws InterruptedException {
// 1 判断
// 1.1 线程间通信,不能用if 只能用while
while (number == 0){
this.wait();
}
// 2 业务逻辑
number--;
System.out.println("消费剩下:" + number);
// 3 通知
this.notifyAll();
}
}
生产者、消费者交替模型
最新推荐文章于 2021-04-09 21:40:42 发布