package 多线程.wait和notify;
import java.util.ArrayList;
import java.util.Random;
/**
* 生产消费模式Demo:包含main方法,用于启动两个线程(一个生产者和一个消费者)。
* Producter类:实现了Runnable接口,代表生产者线程。在run方法中,使用synchronized关键字确保线程安全,
* 在仓库满时等待消费者消费,被唤醒或仓库未满时继续生产,并通过list.notify()方法唤醒消费者线程。
* Consumer类:实现了Runnable接口,代表消费者线程。在run方法中,使用synchronized关键字确保线程安全
* 在仓库为空时等待生产者生产,被唤醒或有库存时进行消费,并通过list.notify()方法唤醒生产者线程。
* Cow类:表示产品,具有一个随机生成的id。
*/
/**
* 每一次唤醒都会去抢占锁的位置,如果运行事件足够长就可以看到这个现象:
* 库存满了-->等待消费
* 消费者-->Cow{id=49869}-->剩余2
* 消费者-->Cow{id=71686}-->剩余1
* 生产者-->Cow{id=44423}目前有2
* 生产者-->Cow{id=32131}目前有3
*/
public class 生产消费模式Demo {
public static void main(String[] args) {
ArrayList<Cow> cowList = new ArrayList<>();
Thread thread01 = new Thread(new Producter(cowList));
Thread thread02 = new Thread(new Consumer(cowList));
thread01.setName("生产者");
thread02.setName("消费者");
thread01.start();
thread02.start();
}
}
// 生产者
class Producter implements Runnable{
ArrayList<Cow> list;
public Producter(ArrayList<Cow> list) {
this.list = list;
}
@Override
public void run() {
while (true){
synchronized (list){
// 当库存为3,仓库满了,不再生产
if(list.size()>=3){
try {
System.out.println("库存满了-->等待消费");
// 放弃当前时间片进入堵塞状态,等待唤醒
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 被唤醒或者仓库未满时继续生产
try {
Thread.sleep(new Random().nextInt(1000)); // 模拟生产速度
Cow cow = new Cow();
list.add(cow);
System.out.println(Thread.currentThread().getName()+"-->"+cow+"目前有"+list.size());
// 生产成功后就可以唤醒消费者继续消费了(无论消费者是否正在wait状态)
list.notify(); // 这里不使用notifyAll 因为有多个消费者可能会导致死锁的问题(业务再复杂的话)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
// 消费者
class Consumer implements Runnable{
ArrayList<Cow> list;
public Consumer(ArrayList<Cow> list) {
this.list = list;
}
@Override
public void run() {
while (true){
synchronized (list){
// 当库存为0时,等待消费者加快生产
if(list.size()==0){
try {
System.out.println("库存为0,等待生产~");
// 放弃当前时间片进入堵塞状态,等待唤醒
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 消费者被唤醒,或者有库存时消费
try {
Thread.sleep(new Random().nextInt(1000)); // 模拟消费速度
Cow remove = list.remove(0);
System.out.println(Thread.currentThread().getName()+"-->"+remove+"-->剩余"+list.size());
list.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
// 牛作为产品
class Cow{
int id;
Random random = new Random();
public Cow() {
this.id = random.nextInt(100000);
}
@Override
public String toString() {
return "Cow{" +
"id=" + id +
'}';
}
}
Demostración del modelo productor-consumidor basado en esperar y notificar
Supongo que te gusta
Origin blog.csdn.net/lfeishumomol/article/details/131917972
Recomendado
Clasificación