• Java基础多线程通讯之生产者消费者模式示例:


    class ProducerConsumerDemo
    {
        public static void main(String[] args)
        {
            Product product = new Product();
            
            new Thread(new Producer(product)).start();
            new Thread(new Consumer(product)).start();
        }
    }

    class Product
    {
        private int count;
        private boolean flag;

        public synchronized void create()
        {
            
            while(this.flag)
            {
                try
                {
                    this.wait();
                }
                catch(Exception e)
                {
                    System.err.println(e.getMessage());
                }
            }
                
            this.count++;    
            System.out.println(Thread.currentThread().getName()+" create -- :"+this.count);
            this.flag = true;
            this.notify();
                
            try
            {
                Thread.sleep(300);
            }
            catch(Exception e)
            {
                System.err.println(e.getMessage());
            }
            
        }
        
        public synchronized void get()
        {
            while(!this.flag)
            {
                try
                {
                    this.wait();
                }
                catch(Exception e)
                {
                    System.err.println(e.getMessage());
                }
            }
                
            System.out.println(Thread.currentThread().getName()+" sale:"+this.count);
            this.flag = false;
            this.notify();
                
            try
            {
                Thread.sleep(600);
            }
            catch(Exception e)
            {
                System.err.println(e.getMessage());
            }
            
        }
    }

    class Producer implements Runnable
    {
        private Product product;
        
        public Producer(Product product)
        {
            this.product = product;
        }
        
        public void run()
        {
            while(true)
            {
                product.create();
            }
        }
    }

    class Consumer implements Runnable
    {
        private Product product;
        
        public Consumer(Product product)
        {
            this.product = product;
        }
        
        public void run()
        {
            while(true)
            {
                product.get();
            }
        }
    }
  • 相关阅读:
    [NOI2004] 郁闷的出纳员
    [洛谷P4556] 雨天的尾巴
    【转】进程、线程、 GIL全局解释器锁知识点整理
    Python3中的SocketServer
    socket 上传文件代码
    python socket 连续send,出现粘包问题
    【转】动态导入模块的两种方法
    【转】面向对象高级语法部分
    python的垃圾回收机制和析构函数__del__
    django 项目使用setting文件里定义的变量方法
  • 原文地址:https://www.cnblogs.com/cxmsky/p/2860931.html
Copyright © 2020-2023  润新知