zoukankan      html  css  js  c++  java
  • 生产消费的经典案例

    package wan;
    
    class wano {
        public static void main(String[] args) throws java.lang.Exception {
    
            Share sh = new Share();
            new Thread(new Producer(sh)).start();//同时启动两个线程
            new Thread(new Consumer(sh)).start();
        }
    }
    
    class Share {
    
        char ch;   //设定ch为全局变量,在整个类中可以用,用于存放生产了的数据给消费调用。
        boolean flag = false; 
    
        public synchronized void set() {
            char[] cha = { 'a', 'b', 'c', 'd', 'e', 'f', 'g' };
    
            for (char chari : cha) {  //等待和唤醒必须写在for循环里面
    
                if (flag) {
    
                    try {
                        wait(); //等待消费取数
                    } catch (InterruptedException e) {
                    }
    
                }
    
                this.ch = chari;
                flag = true;
                notify();  //唤醒消费程序
            }
    
        }
    
        public synchronized void get() {
            if (!flag) {
                try {
                    wait();  //等待生成
                } catch (InterruptedException e) {
                }
    
            }
            System.out.println("ch = " + this.ch);
            flag = false;
            notify();  //唤醒生产程序
        }
    }
    
    class Producer implements Runnable {
        Share sh = null;
    
        public Producer(Share sh) {
            this.sh = sh;
        }
    
        public void run() {
    
            this.sh.set();
        }
    }
    
    class Consumer implements Runnable {
        Share sh = null;
    
        public Consumer(Share sh) {
            this.sh = sh;
        }
    
        public void run() {
            for (int i = 0; i < 4; i++)
                this.sh.get();
        }
    }
  • 相关阅读:
    C语言程序设计第一次作业
    C语言I博客作业09
    C语言I博客作业08
    C语言I博客作业07
    C语言I博客作业06
    C语言I博客作业05
    C语言II博客作业03
    C语言II博客作业02
    C语言II博客作业01
    学期总结
  • 原文地址:https://www.cnblogs.com/dengnapianhuahai/p/5776388.html
Copyright © 2011-2022 走看看