zoukankan      html  css  js  c++  java
  • Java Consumer and Producer demo

    import java.util.Random;
    import java.util.concurrent.LinkedBlockingQueue;
    class producer
    {
        Random rdm = new Random();
        void produce( LinkedBlockingQueue<Integer> productlist)
        {
             while(true)
             {
                 if(productlist.size()<101)
                 {
                     productlist.add(rdm.nextInt(100));
                     System.out.println(Thread.currentThread().getName() +" produce number:" + productlist.peek());
                 }
             }
        }
    }
    class consumer
    {
        void consume(LinkedBlockingQueue<?> productlist)
        {
             while(true)
             {
                 if(productlist.size()>0)
                 {
                     System.out.println(Thread.currentThread().getName() +" consume number:" + productlist.poll());
                 }
             }
        }
    }

    //producer and customer demo
    public class ThreadDemo {
        public static void main(String[] args)
        {
            final LinkedBlockingQueue<Integer> productlist = new LinkedBlockingQueue<Integer>();;
            final producer p = new producer();
            new Thread(  new Runnable(){
                        public  void run()
                        {
                             p.produce(productlist);
                        }
                    }
                    ).start();
            for(int i=1;i<3;i++)
            {
                final consumer c = new consumer();
                new Thread(new Runnable(){
                        public void run()
                        {
                            c.consume(productlist);
                        }
                }).start();
            }
        }
    }

    one question: 为什么在线程中使用到的外部变量,如p,productlist 等都需要设置成final呢?

    同事做了调研,其中一个较为合理的理由是,这个线程后面的其实是一个内部类,而这个内部类引用的这个对象,它是需要自己复制到自己内部的。

    而如果它复制的这个对象允许改变指向的对象(或值本身),那么它们就会失去数据的一致性。

    Looking for a job working at Home about MSBI
  • 相关阅读:
    第9课
    FreeRTOS 定时器组
    FMC—扩展外部 SDRAM
    FreeRTOS 事件标志组
    第8课
    FreeRTOS 系统时钟节拍和时间管理
    第七课 线性表的顺序存储结构
    手把手教你调试Linux C++ 代码(一步到位包含静态库和动态库调试)
    Windows GUI代码与Windows消息问题调试利器
    谈谈数据挖掘和机器学习
  • 原文地址:https://www.cnblogs.com/huaxiaoyao/p/4288778.html
Copyright © 2011-2022 走看看