当前位置: 首页 > news >正文

线程间通信(生产者和消费者案例)

一、传统的线程间通信的方式

使用

Object:

        synchronized:阻塞锁

        wait():阻塞当前队列

        notifyAll():唤醒所有阻塞队列

package ProduceAndConsumer;

/*
 * @Auther:生产者消费者案例1
 * @Date:2024/6/20
 * @Description:qinhao
 * @VERSON:1.8
 */


public class PACTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        new Thread(new Product(clerk)).start();
        new Thread(new Consumer(clerk)).start();
    }
}

class Clerk{
    private int count = 0;
    private static final int maxCount = 3;
    public synchronized void product() throws InterruptedException {
        if(count < maxCount){
            Thread.sleep(500);
            count++;
            System.out.println(Thread.currentThread().getName() + "生产了一个商品,当前商品有:" + count);
            notifyAll();
        }else{
            System.out.println(Thread.currentThread().getName() + "仓库已满");
            this.wait();
        }
    }

    public synchronized void consumer() throws InterruptedException {
        if(count > 0){
            Thread.sleep(500);
            count--;
            System.out.println(Thread.currentThread().getName() + "消费了一个商品,当前商品有:" + count);
            notifyAll();
        }else{
            System.out.println(Thread.currentThread().getName() + "缺货");
            this.wait();
        }
    }
}


//生产者
class Product implements Runnable{
    private Clerk clerk;
    Product(Clerk clerk){this.clerk = clerk;}

    @Override
    public void run() {
        while(true){
            try {
                clerk.product();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}


//消费者
class Consumer implements Runnable{
    private Clerk clerk;
    Consumer(Clerk clerk){this.clerk = clerk;}

    @Override
    public void run() {
        while(true){
            try {
                clerk.consumer();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

二、Condition控制线程通信

使用 :

lock :

        lock():加锁

        unlock():释放锁

condition:

        await():阻塞当前线程

        signalall():唤醒阻塞线程

package ProduceAndConsumer;

/*
 * @Auther:勤学好问
 * @Date:2024/6/20
 * @Description:qinhao
 * @VERSON:1.8
 */


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PACTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
        new Thread(new Product(clerk)).start();
        new Thread(new Consumer(clerk)).start();
    }
}

class Clerk {
    private int count = 0;
    private static final int maxCount = 3;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void product() throws InterruptedException {
        //枷锁
        lock.lock();
        //确保锁释放
        try {
            if (count < maxCount) {
                Thread.sleep(500);
                count++;
                System.out.println(Thread.currentThread().getName() + "生产了一个商品,当前商品有:" + count);
                condition.signalAll();
            } else {
                System.out.println(Thread.currentThread().getName() + "仓库已满");
                condition.await();
            }
        } finally {
            lock.unlock();
        }
    }

    public void consumer() throws InterruptedException {
        //枷锁
        lock.lock();
        //确保锁会释放
        try {
            if (count > 0) {
                Thread.sleep(500);
                count--;
                System.out.println(Thread.currentThread().getName() + "消费了一个商品,当前商品有:" + count);
                condition.signalAll();
            } else {
                System.out.println(Thread.currentThread().getName() + "缺货");
                condition.await();
            }
        } finally {
            lock.unlock();
        }
    }
}

class Product implements Runnable {
    private Clerk clerk;

    Product(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true) {
            try {
                clerk.product();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

class Consumer implements Runnable {
    private Clerk clerk;

    Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true) {
            try {
                clerk.consumer();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

相关文章:

  • Python 获取class_name win32gui
  • 单片机课设-基于单片机的电子时钟设计(仿真+代码+报告)
  • Vim基础操作:常用命令、安装插件、在VS Code中使用Vim及解决Vim编辑键盘错乱
  • 八股文之JVM
  • Apple Phone Memory
  • 【转载】使用 .NET Upgrade Assistant(升级助手)升级 .NET 老旧版本项目
  • 车载测试系列:车载测试流程
  • C++基础知识——命名空间
  • 贪吃蛇——c语言版
  • Joplin Typora 粘贴图片 | 当使用Typora作为Joplin编辑器时,如何粘贴图片并上传到Joplin服务器,替换链接
  • MySQL中动态权限和角色管理权限的异同?
  • AI 已经在污染互联网了。。赛博喂屎成为现实
  • 【SPIE独立出版 | 往届均已完成EI检索】2024云计算、性能计算与深度学习国际学术会议(CCPCDL 2024)
  • MySQL动态权限详解
  • RabbitMQ安装配置,封装工具类,发送消息及监听
  • 汽车IVI中控开发入门及进阶(三十一):视频知识扫盲
  • 2024年虚拟现实、图像和信号处理国际学术会议(ICVISP 2024)
  • AI音乐大模型:是颠覆还是助力?
  • 大众标准化杂志大众标准化杂志社大众标准化编辑部2024年第10期目录
  • 04. Java 多线程的创建
  • 近4小时会谈、3项联合声明、20多份双边合作文本,中俄元首今年首次面对面会晤成果颇丰
  • 警惕“全网最低价”等宣传,市监总局和中消协发布直播消费提示
  • 正荣地产:公司控股股东已获委任联合清盘人
  • 多个“网约摩托车”平台上线,工人日报:安全与监管不能掉队
  • 巴基斯坦所有主要城市宣布进入紧急状态,学校和教育机构停课
  • 奥迪4S店内揭车衣时遭“连环车损”,双方因赔偿分歧陷僵局