并发编程之生产者和消费者问题

本文探讨了Java中线程通信的示例,通过`Data`类的`synchronized`方法实现生产者和消费者线程的互斥操作,避免了虚假唤醒。重点讲解了如何使用`wait()`和`notifyAll()`正确处理资源争夺,确保任务按预期执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简单的线程通信,一个线程对数字进行增加操作、另一个线程对线程进行减少操作。

简单解释:线程A对数字进行减少操作,但不会一直让这个数字减少下去。当减少到设定的条件,让其等待,通知其他线程获得该资源。

package com.ProductAndCustomer;

/**
 * 线程之间的通信,生产者和消费者问题
 */
public class Product {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"B").start();
    }
}


//等待,业务,通知
class Data{
    //资源类
    private int num = 0;

    //增加操作
    public synchronized void increment() throws InterruptedException {
        if(num != 0){
            //等待
            this.wait();
        }
        num ++;
        System.out.println(Thread.currentThread().getName()+"=>"+num);
        //通知其他线程,+1结束
        this.notifyAll();
    }

    //减少操作
    public synchronized void decrement() throws InterruptedException {
        if(num == 0){
            //等待
            this.wait();
        }
        num --;
        System.out.println(Thread.currentThread().getName()+"=>"+num);
        //通知其他线程,-1结束
        this.notifyAll();
    }
}

测试
在这里插入图片描述

在多几个线程

package com.ProductAndCustomer;

/**
 * 线程之间的通信,生产者和消费者问题
 */
public class Product {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"C").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"D").start();
    }
}


//等待,业务,通知
class Data{
    //资源类
    private int num = 0;

    //增加操作
    public synchronized void increment() throws InterruptedException {
        if(num != 0){
            //等待
            this.wait();
        }
        num ++;
        System.out.println(Thread.currentThread().getName()+"=>"+num);
        //通知其他线程,+1结束
        this.notifyAll();
    }

    //减少操作
    public synchronized void decrement() throws InterruptedException {
        if(num == 0){
            //等待
            this.wait();
        }
        num --;
        System.out.println(Thread.currentThread().getName()+"=>"+num);
        //通知其他线程,-1结束
        this.notifyAll();
    }
}

测试结果
在这里插入图片描述
这里会出现虚假唤醒
查看开发文档可知、需要修改判断语句 if修改为while
在这里插入图片描述
修改后的代码

package com.ProductAndCustomer;

/**
 * 线程之间的通信,生产者和消费者问题
 */
public class Product {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"C").start();

        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"D").start();
    }
}


//等待,业务,通知
class Data{
    //资源类
    private int num = 0;

    //增加操作
    public synchronized void increment() throws InterruptedException {
        while(num != 0){
            //等待
            this.wait();
        }
        num ++;
        System.out.println(Thread.currentThread().getName()+"=>"+num);
        //通知其他线程,+1结束
        this.notifyAll();
    }

    //减少操作
    public synchronized void decrement() throws InterruptedException {
        while(num == 0){
            //等待
            this.wait();
        }
        num --;
        System.out.println(Thread.currentThread().getName()+"=>"+num);
        //通知其他线程,-1结束
        this.notifyAll();
    }
}

测试结果
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

乡下小哥编程

整理不易、多谢支持

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

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

打赏作者

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

抵扣说明:

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

余额充值