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
  • 相关阅读:
    centos 6.5 中设置mysql 5.1.73 主从同步配置过程
    13-jQuery事件绑定和常用鼠标事件
    12-jQuery获取相关尺寸
    11-jQuery简介和选择器
    10-js对象、数组
    09-js定时器、函数
    08-js流程控制、循环、元素操作
    07-js数据类型
    06-JavaScript简介
    05-CSS浮动、定位、页面布局
  • 原文地址:https://www.cnblogs.com/huaxiaoyao/p/4288778.html
Copyright © 2011-2022 走看看