zoukankan      html  css  js  c++  java
  • java多线程之wait和notify协作,生产者和消费者

    这篇直接贴代码了

    package cn.javaBase.study_thread1;
    
    class Source {
        public static int num = 0; //假设这是馒头的数量
    }
    
    class Producer implements Runnable {
        private Object obj;
        
        public Producer(Object obj) {
            this.obj = obj;
        }
        
        @Override
        public void run() {
            synchronized (obj) {
                while (true) {
                    if (Source.num >= 6) { //馒头的数量>=6个的时候,就停下来不生产了,通知别人来消费
                        obj.notify();
                        System.out.println("满了,消费吧");
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    
                    Source.num++;
                    System.out.println("已经生产了:"+ Source.num + "个");
                }
            }
        }
    }
    
    class Consumer implements Runnable{
        private Object obj;
        
        public Consumer(Object obj) {
            this.obj = obj;
        }
    
        @Override
        public void run() {
            synchronized (obj) {
                while (true) {
                    if (Source.num == 0) {  //馒头的数量==0个的时候,就停下不消费了,通知别人该生产了
                        obj.notify();
                        System.out.println("没了,生产吧。");
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    
                    Source.num--;
                    System.out.println("剩下了:"+ Source.num + "个");
                }
            }
        }
    }
    
    public class MyProducerConsumer {
    
        public static void main(String[] args) throws InterruptedException {
            Object a = new Object();
            
            Producer p = new Producer(a);
            Consumer c = new Consumer(a);
            
            new Thread(p).start();
            Thread.sleep(200);  //为了保证先生产,再消费, 不用也可以
            new Thread(c).start();
            
        }
    }

    因为思想跟上一篇的Java多线程之wait和notify:http://www.cnblogs.com/WNof11020520/p/8780875.html

    讲的差不多,所以在这里就不累赘了。

  • 相关阅读:
    基于Python的人脸动漫转换
    let 与 var的区别
    【LeetCode】汇总
    【HDU】4632 Palindrome subsequence(回文子串的个数)
    【算法】均匀的生成圆内的随机点
    【LeetCode】725. Split Linked List in Parts
    【LeetCode】445. Add Two Numbers II
    【LeetCode】437. Path Sum III
    【LeetCode】222. Count Complete Tree Nodes
    【LeetCode】124. Binary Tree Maximum Path Sum
  • 原文地址:https://www.cnblogs.com/WNof11020520/p/8794047.html
Copyright © 2011-2022 走看看