zoukankan      html  css  js  c++  java
  • Object.wait()实现生产者消费者模式

    主调用程序:

    public class MainDemo {
        public static void main(String[] args) {
            Box box=new Box();
    
            Product product=new Product(box);
            Customer customer =new Customer(box);
    
            Thread th1=new Thread(product);
            Thread th2=new Thread(customer);
    
            th1.start();
            th2.start();
    
        }
    }

    共享资源类:

    /*
    * 共享数据区
    * */
    public class Box {
        private int milk;
        private boolean state=false;
    
        /*
        * 加锁调用
        * */
        public synchronized void put(int milk)
        {
            if (state){
                try {
                    /* 事件锁:
                    * 1.不带参数:导致当前线程等待,直到另一个线程调用该对象的 notify()方法或 notifyAll()方法。
                    * 2.带参数重载:导致当前线程等待,直到另一个线程调用该对象的 notify()方法或 notifyAll()方法,或指定的时间已过。
                    * */
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    
            this.milk=milk;
    
            System.out.println("放入:"+this.milk);
    
            this.state=true;
    
            /*
            * 唤醒正在等待对象监视器的所有线程。
            * */
            notifyAll();
        }
    
        public synchronized void get(){
            if (!state){
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    
            System.out.println("取出:"+milk);
    
            state=false;
    
            notifyAll();
        }
    }

    生产者:

    /*
    * 生产者类
    * */
    public class Product implements Runnable {
        private Box box;
    
        public Product(Box box) {
            this.box = box;
        }
    
        @Override
        public void run() {
            for (int i=1;i<11;i++){
                box.put(i);
            }
        }
    }

    消费者:

    /*
    * 消费者类
    * */
    public class Customer implements Runnable {
        private Box box;
    
        public Customer(Box box) {
            this.box = box;
        }
    
        @Override
        public void run() {
            while (true){
                box.get();
            }
        }
    }
  • 相关阅读:
    Canvas鼠标点击特效(富强、民主...)、收藏
    mysql实现当前行的值累加上一行的值
    HTML生成横向的PDF
    Java iText+FreeMarker生成PDF(HTML转PDF)
    HTML图片点击放大---关闭
    HTML页面通过JS跨域调用,子传父
    查询结果中出现行号(适用于按名次排序)
    在Nginx和Apache服务器配置https
    Rinetd 端口转发工具
    lsyncd使用中遇到的问题
  • 原文地址:https://www.cnblogs.com/zhuyapeng/p/13825777.html
Copyright © 2011-2022 走看看