• 生产者消费者-Java代码实现


    import java.util.LinkedList;
    
    class Storage{
        private static final int MAX = 100;
        LinkedList<Object> list = new LinkedList<>();
    
        public void produce(int num) throws Exception{
            synchronized(list){
                while(list.size() + num > MAX){
                    System.out.println("仓库太小,生产装不下!!");
                    list.wait();
                }
                for(int i=0; i<num; i++)
                    list.add(new Object());
                System.out.println("生产了---" + num);
                list.notifyAll();
            }
        }
        public void consume(int num) throws Exception{
            synchronized(list){
                while(list.size() < num){
                    System.out.println("仓库的库存不够");
                    list.wait();
                }
                for(int i=0; i<num; i++)
                    list.remove();
                System.out.println("消费了---" + num);
                list.notifyAll();
            }
        }
    }
    
    class Producer implements Runnable{
        private int num;
        private Storage storage;
        public Producer(int num, Storage storage){
            this.num = num;
            this.storage = storage;
        }
        public void produce(){
            try{
                storage.produce(num);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        public void run(){
            produce();
        }
    }
    
    class Consumer implements Runnable{
        private int num;
        private Storage storage;
        public Consumer(int num, Storage storage){
            this.num = num;
            this.storage = storage;
        }
        public void consume(){
            try{
                storage.consume(num);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        public void run(){
            consume();
        }
    }
    
    public class Pro_Con{
        public static void main(String[] args){
            Storage st = new Storage();
    
            Producer p1 = new Producer(10, st);
            Producer p2 = new Producer(80, st);
    
            Consumer c1 = new Consumer(40, st);
            Consumer c2 = new Consumer(70, st);
    
            new Thread(c1, "消费者1").start();
            new Thread(c2, "消费者2").start();
            new Thread(p1, "生产者2").start();
            new Thread(p2, "生产者2").start();
        }
    }
    
  • 相关阅读:
    webservice的几种调用方式
    捕获的异常到控制台的的信息转为String输出,在保存日志方面有用
    IO文件的读取与写入
    eclipse修改内存大小
    Oracle序列的创建与删除
    NFS挂载-实现文件共享
    arraylList.add(int,obj)的底层是怎么样的??
    Oracle修改表字段数据类型
    SVN版本库打包迁移备份恢复
    linux中tar详解
  • 原文地址:https://www.cnblogs.com/lanqiu5ge/p/9453601.html
Copyright © 2020-2023  润新知