Java Consumer and Producer Demo

Source: Internet
Author: User

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: Why do the external variables used in the thread, such as p,productlist, need to be set to final?

Colleagues do research, one of the more reasonable reason is that after this thread is actually an internal class, and this internal class refers to this object, it is necessary to copy themselves into their own internal.

And if the object it replicates allows the object to be changed (or the value itself), then they lose the consistency of the data.

Java Consumer and Producer demo

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.