zoukankan      html  css  js  c++  java
  • 生产者消费者

    package com.kaibing.design;
    
    public class ProductorAndCustomer {
    
    
        public static void main(String[] args) {
            Clerk clerk = new Clerk();
    
            Productor productor = new Productor(clerk);
            Customer customer = new Customer(clerk);
    
            new Thread(productor, "生产者A:").start();
            new Thread(customer, "消费者A:").start();
    
            new Thread(productor, "生产者B:").start();
            new Thread(customer, "消费者B:").start();
        }
    
        static class Clerk {//店员类
    
            private int product = 0;
    
            public synchronized void get() {//进货
                while (product >= 1) {//容量为1
                    System.out.println("库存已满");
                    try {
                        this.wait();//等待:为了避免虚假唤醒,wait在循环中使用
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //进货
                System.out.println("库存" + ++product);
                this.notifyAll();//唤醒
            }
    
            public synchronized void sale() {//卖货
                while (product <= 0) {
                    System.out.println("库存已空");
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("卖货" + --product);
                this.notifyAll();//唤醒
            }
        }
    
        static class Productor implements Runnable {
    
            private Clerk clerk;
    
            public Productor(Clerk clerk) {
                this.clerk = clerk;
            }
    
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    clerk.get();//消费货物
                }
            }
        }
    
        static class Customer implements Runnable {
    
            private Clerk clerk;
    
            public Customer(Clerk clerk) {
                this.clerk = clerk;
            }
    
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
    
                    clerk.sale();//消费货物
                }
            }
        }
    
    
    }
  • 相关阅读:
    Springboot注解@Scheduled定时任务的使用
    Springboot整合WebSocket和RabbitMQ实现服务器消息推送
    Springboot集成WebSocket实现消息推送功能
    RabbitMq: 主题交换机的使用(Topic Exchange)
    Rabbitmq: @RabbitListener 和 @RabbitHandler 搭配使用
    RabbitMQ开启 mqtt 协议
    @Import的简单使用
    idea快速生成对应数据库的实体类
    HttpClient封装工具类
    TypeScript基本概念
  • 原文地址:https://www.cnblogs.com/kaibing/p/9258114.html
Copyright © 2011-2022 走看看