线程协作

线程通信

生产者和消费者问题

应用场景:生产者和消费者问题

  • 假设仓库中只能存放一件产品,生产者将生产出来的产品放入仓库﹐消费者将仓库中产品取走消费.
  • 如果仓库中没有产品,则生产者将产品放入仓库,否则停止生产并等待,直到仓库中的产品被消费者取走为止.
  • 如果仓库中放有产品,则消费者可以将产品取走消费,否则停止消费并等待直到仓库中再次放入产品为止.

这是一个线程同步问题生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件.

  • 对于生产者,没有生产产品之前,要通知消费者等待﹒而生产了产品之后﹐又需要马上通知消费者消费
  • 对于消费者﹐在消费之后,要通知生产者已经结束消费﹐需要生产新的产品以供消费.
  • 在生产者消费者问题中﹐仅有synchronized是不够的
    • synchronized可阻止并发更新同一个共享资源,实现了同步
    • synchronized 不能用来实现不同线程之间的消息传递(通信)

Java提供了几个方法解决线程之间的通信问题

image-20230227164001255

注意:均是Object类的方法,都只能在同步方法或者同步代码块中使用,否则会抛出异常IllegalMonitorStateException

解决方式

  1. 并发协作模型“生产者/消费者模式”--->管程法
    • 生产者:负责生产数据的模块(可能是方法﹐对象﹐线程﹐进程);
    • 消费者:负责处理数据的模块(可能是方法﹐对象,线程,进程);
    • 缓冲区:消费者不能直接使用生产者的数据﹐他们之间有个“缓冲区生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据
  2. 并发协作模型“生产者/消费者模式”--->信号灯法
package com.cz.demo4;

/**
 * @author 卓亦苇
 * @version 1.0
 * 2023/2/27 21:26
 */
//测试:生产者与消费者模型   利用缓冲区解决:管程法
//生产者,消费者,产品,缓冲区
public class TestPC {
    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();

        new Producer(synContainer).start();
        new Consumer(synContainer).start();

    }
}

//生产者
class Producer extends Thread{
    SynContainer container;
    public Producer(SynContainer container){
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {

            container.push(new Chicken(i));
            System.out.println("生产了第"+i+"只鸡");
        }

    }
}

//消费者
class Consumer extends Thread{
    SynContainer container;
    public Consumer(SynContainer container){
        this.container = container;
    }

    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {

            container.pop();
            System.out.println("消费了-------第"+i+"只鸡");
        }

    }

}

//产品
class Chicken{
    int id; //产品编号

    public Chicken(int id) {
        this.id = id;
    }
}

//缓冲区
class SynContainer{
    //需要一个容器大小
    Chicken[] chickens = new Chicken[10];
    //产品数
    int count=0;

    //生产者放入产品
    public synchronized void push (Chicken chicken){

        //如果容器已经满了通知消费者消费产品
        if(count==chickens.length){
            //通知消费者进行消费
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        
        //容器没有满,将传入的产品放进容器中
        chickens[count]=chicken;
        count++;
        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Chicken pop(){
        //判断容器中是否有产品,是否能进行消费
        if (count==0){
            //等待生产者生产
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        //如果可以消费

        count--;
        Chicken chicken = chickens[count];

        //吃完了,通知生产者生产
        this.notifyAll();
        return chicken;

    }

}
package com.cz.demo4;

import java.sql.SQLOutput;

/**
 * @author 卓亦苇
 * @version 1.0
 * 2023/2/28 9:40
 */
//测试消费者生产者问题2,信号灯法,标志位解决
public class TestPC2 {
    public static void main(String[] args) {
        TV tv = new TV();
        new Player(tv).start();
        new Watcher(tv).start();
    }
}

//生产者-->演员
class Player extends Thread {
    TV tv;
    public Player(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            if(i%2==0) {
                this.tv.play("三体");
            }else {
                this.tv.play("天线宝宝");
            }
        }
    }
}
//消费者-->观众
class Watcher extends Thread{
    TV tv;

    public Watcher(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            this.tv.watch();
        }
    }
}
//产品-->节目
class TV{
    //演员表演,观众等待
    //观众观看,演员等待
    String voice; //表演的节目
    boolean flag = true;


    //表演
    public synchronized void play(String voice){
        if (!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }
        System.out.println("演员表演了"+voice);
        this.notifyAll();
        this.voice=voice;
        this.flag=!this.flag;
    }


    //观看
    public synchronized void watch(){
        if (flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }
        System.out.println("观看了"+voice);
        this.notifyAll();
        this.flag=!this.flag;
    }


}
posted @   卓亦苇  阅读(1)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类
点击右上角即可分享
微信分享提示