Java基础进阶多线程-生产者和消费者模式

1、什么是“生产者和消费者模式”?

  • 生产线程负责生产,消费线程负责消费
  • 生产线程和消费线程要达到均衡
  • 这是一种特殊的业务需求,在这种特殊的情况下需要使用wait方法和notify方法

2、wait和notify方法不是线程对象的方法,是普通java对象都有的方法
3、wait和notify方法建立在线程同步的基础之上因为多线程要同时操作一个仓库有线程安全问题
4、wait方法作用:o.wait()让正在o对象上活动的线程t进入等待状态并且释放掉t线程之前占有的o对象的锁
5、notify方法作用:o.notify()让正在o对象上等待的线程唤醒,只是通知,不会释放o对象上之前占有的锁
6、模拟需求:

  • 仓库我们采用List集合
    List集合中假设只能存储一个元素
    1个元素就表示仓库满l
    如果List集合中元素个数是0,就表示仓库空了
    保证List集合中永远都是最多存储一个元素了
    必须做到,生产一个,消费一个
    在这里插入图片描述
    在这里插入图片描述

示例代码01:

public class ThreadTest16 {

    public static void main(String[] args) {

        //创建一个仓库对象,共享的
        List list = new ArrayList();
        //创建对象
        //创建生产者对象
        Thread t1 = new Producter(list);
        //创建消费者对象
        Thread t2 = new Consumer(list);
        t1.setName("生产者线程");
        t2.setName("消费者线程");

        //启动线程
        t1.start();
        t2.start();
    }
}

//生产者线程
class Producter extends Thread{
    private List list;
    public Producter(List list){
        this.list = list;
    }

    public void run(){

        while(true) {
            synchronized (list) {
                if (list.size() > 0) {
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Object obj = new Object();
                list.add(obj);
                System.out.println(Thread.currentThread().getName() + "--->" + obj);
                //线程唤醒
                list.notifyAll();
            }
        }
    }
}

//消费者线程
class Consumer extends Thread{

    private List list;
    public Consumer(List list){
        this.list = list;
    }
    public void run(){

        while(true){
            synchronized (list) {
                if (list.size() == 0) {
                    try {
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Object obj = list.remove(0);
                System.out.println(Thread.currentThread().getName() + "--->" + obj);
                list.notifyAll();
            }
        }
    }
}

运行结果:

在这里插入图片描述

使用生产者和消费者模式实现,交替输出:
假设只有两个线程,输出以下结果:

  • t1—>1
    t2—>2
    t3—>3
    t4—>4
    t5—>5
    t6—>6
    t7—>7
    要求:必须交替执行,并且t1线程负责输出奇数,t2线程输出偶数
    两个线程共享一个数字,每个线程执行时都要对这个数字进行:++

示例代码02:

public class ThreadTest {
    public static void main(String[] args) {

        //创建数字类对象
        Num num = new Num();
        //创建生产者对象
        Thread t1 = new Producter(num);

        //创建消费者对象
        Thread t2 = new Consumer(num);

        //修改线程名字
        t1.setName("t1");
        t2.setName("t2");

        //启动线程
        t1.start();
        t2.start();

    }
}

//共享数据
class Num{
    int i = 1;


}
//生产者线程
class Producter extends Thread{

    private Num num;
    public Producter(Num num){
        this.num = num;
    }
    public void run(){

        while(true){
            synchronized (num) {
                if ((num.i % 2) == 0) {
                    try {
                        num.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + "--->" + num.i++);
                try {
                    //延迟1秒输出
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                num.notifyAll();
            }
        }
    }
}
//消费者线程
class Consumer extends Thread{

    private Num num;
    public Consumer(Num num){
        this.num = num;
    }
    public void run(){

        while(true){
            synchronized (num) {
                if ((num.i % 2) == 1) {
                    try {
                        num.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println(Thread.currentThread().getName() + "--->" + num.i++);
                try {
                    //延迟一秒输出
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                num.notifyAll();
            }
        }
    }
}

运行结果:

在这里插入图片描述

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
生产者消费者问题是一种经典的多线程同步问题,主要涉及到生产者消费者之间的数据交换和同步。 在Java中,可以使用多种方式来实现生产者消费者问题的解决方案,其中最常用的方式是使用wait()和notify()方法来实现线程间的同步。 下面是一个简单的示例,演示了如何使用wait()和notify()方法来实现生产者消费者问题的解决方案: ``` import java.util.LinkedList; import java.util.Queue; public class ProducerConsumer { private Queue<Integer> buffer = new LinkedList<>(); private final int capacity = 5; public void produce() throws InterruptedException { int value = 0; while (true) { synchronized (this) { while (buffer.size() == capacity) wait(); System.out.println("Producer produced-" + value); buffer.add(value++); notify(); Thread.sleep(1000); } } } public void consume() throws InterruptedException { while (true) { synchronized (this) { while (buffer.size() == 0) wait(); int val = buffer.poll(); System.out.println("Consumer consumed-" + val); notify(); Thread.sleep(1000); } } } } ``` 在上面的示例中,ProducerConsumer类表示生产者消费者问题的解决方案。这个类有一个buffer队列,它是一个FIFO队列,用于存储生产者生产的数据。 produce()方法表示生产者的行为,它使用一个while(true)循环来不断地生产数据。在每次生产之前,它首先检查buffer队列是否已满。如果buffer队列已满,则调用wait()方法来等待消费者线程消费数据。如果buffer队列未满,则将生产的数据添加到buffer队列中,并调用notify()方法通知消费者线程可以消费数据了。 consume()方法表示消费者的行为,它使用一个while(true)循环来不断地消费数据。在每次消费之前,它首先检查buffer队列是否为空。如果buffer队列为空,则调用wait()方法来等待生产者线程生产数据。如果buffer队列不为空,则从buffer队列中取出一个数据,并调用notify()方法通知生产者线程可以生产数据了。 在上面的示例中,使用了synchronized关键字来实现线程的同步。synchronized关键字可以确保在同一时间只有一个线程可以执行被synchronized关键字包裹的代码块。wait()方法可以让线程等待,直到被notify()方法唤醒。notify()方法可以唤醒一个等待的线程。如果有多个线程等待,则只有一个线程会被唤醒。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

五度鱼学Java

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值