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