美文网首页
多线程之生产者与消费者

多线程之生产者与消费者

作者: 是我真的是我 | 来源:发表于2019-11-05 23:20 被阅读0次

    Box

    public class Box {
        private int apple = 0;
    
        public static void main(String[] args) {
            Box box = new Box();
            Thread product = new Thread(new Product(box), "生产者1");
            Thread consumer = new Thread(new Consumer(box), "消费者1");
            Thread consumer2 = new Thread(new Consumer(box), "消费者2");
            product.start();
            consumer.start();
            consumer2.start();
        }
    
        public synchronized void add(){
            while (apple == 5){
                try {
                    wait();
                }catch (Exception e){
    
                }
    
            }
            apple ++;
            System.out.println("生产苹果成功");
            notifyAll();
        }
    
        public synchronized void put(){
            while (apple == 0){
                try {
                    wait();
                }catch (Exception e){
    
                }
            }
            apple --;
            notifyAll();
        }
    }
    

    Product

    public class Product implements Runnable {
        Box box;
    
        public Product(Box b){
            box = b;
        }
    
        @Override
        public void run(){
            for (int i=0; i<10; i++){
                try {
                    box.add();
                    int rt = (int)(Math.random() * 100);
                    Thread.sleep(rt + 100);
                }catch (Exception e){
    
                }
    
            }
    
        }
    }
    

    Consumer

    package Thread;
    
    public class Consumer implements Runnable {
        Box box;
    
        public Consumer(Box b){
            box = b;
        }
    
        @Override
        public void run(){
            for (int i=0; i<5; i++){
                try {
                    box.put();
                    System.out.println(Thread.currentThread().getName() + "吃了一个苹果");
                    int rt = (int)(Math.random() * 100);
                    Thread.sleep(rt + 400);
                }catch (Exception e){
    
                }
            }
    
        }
    }
    
    运行结果展示

    相关文章

      网友评论

          本文标题:多线程之生产者与消费者

          本文链接:https://www.haomeiwen.com/subject/dllybctx.html