什么是生产者和消费者?
就是你去吃包子,包子铺就是生产者,你就是消费者。简单的说就是生产者负责造,消费者负责耗。
需要解决的问题
- 生产者过度生产问题
- 通知机制
- 消费者过度消费
- 避免产生死锁
进化图
传统写法
synchronized
/*
* 生产者消费者【传统版】
* synchronized、wait、notify
* 一个初始值0,两个线程交替操作五轮,一个加一,一个减一
* 思想:
* 1.线程操作资源类
* 2.判断->干活->通知
*/
class Data{
private int num = 0;
public synchronized void increment(){
//判断
while(num!=0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//干活
num++;
System.out.println(Thread.currentThread().getName()+" invoked increment 操作,num="+num);
//通知
this.notifyAll();
}
public synchronized void decrement(){
//判断
while(num==0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//干活
num--;
System.out.println(Thread.currentThread().getName()+" invoked decrement 操作,num="+num);
//通知
this.notifyAll();
}
}
public class ProductConsumer_1 {
public static void main(String[] args) {
Data data = new Data();
new Thread(()->{
for (int i = 1; i <= 5; i++) {
data.increment();
}
},"线程1").start();
new Thread(()->{
for (int i = 1; i <= 5; i++) {
data.decrement();
}
},"线程2").start();
}
}
运行结果
Lock
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/*
* 生产者消费者【传统版】
* lock、await、signa