Java Consumer and Producer demo

时间:2021-08-15 03:58:01

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呢?

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

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