Consumer producer model-Java thread Simulation

Source: Internet
Author: User
During this time, I have been working as a Java course TA with my tutor. Every day, I am bored with those boring questions! Today I finally met them with a difficult question:
Solve a single producer, single consumer problem using wait () and consumer y (). the producer must not overflow the generator's buffer, which can happen if the producer is faster than the consumer. if the consumer is faster than the producer, then it must not read the same data more than once. do not assume anything about the relative speeds of the producer or consumer.

The following is the corresponding code. The key is multithreading. In this example, not only one producer and one consumer are allowed, but any number of consumers are allowed.

// Product
Class produce
{
Private string name;

Public produce (string name)
{
This. Name = Name;
}

Public String tostring ()
{
Return name;
}
}
 
/** The respiratory class * uses an array to represent the cyclic queue to store the product */
Class Storage
{

Private Static int capacity = 11;
Private produce []
Data = new produce [capacity];
Private int front = 0;
Private int rear = 0;
Public Storage (final int capacity)
{
This. capacity = capacity + 1;
}
/*** Consume a product */
Public produce
Consume () throws interruptedexception
{
Synchronized (this)
{
While (front = rear)
{
This. Wait ();
}
Int access = front;
Front = (front + 1 + capacity) % capacity;
Produce = data [access];
System. Out. println ("consumer [" + thread. currentthread (). getname () + "] consume:" + produce );
System. Out. println ("storage condition: Count =" + (Rear + capacity-Front) % capacity );
This. Policy ();
Return produce;
}
}
/*** Produce a product */
Public void produce (produce) throws interruptedexception
{
Synchronized (this)
{
While (Rear + 1) % capacity = front)
{
This. Wait ();
}
Data [rear] = produce; Rear = (Rear + 1) % capacity;
System. Out. println ("producer [" + thread. currentthread (). getname () + "] produce:" + produce );
System. Out. println ("storage condition: Count =" + (Rear + capacity-Front) % capacity );
This. Policy ();
}
}
}
/**
* Producer class, which uses threads to simulate producer Behavior
*/
class Producer extends Thread
{
private Storage storage;
private static int produceName=0;
  
    public Producer(Storage storage,String name)
   {
     super(name);
     this.storage=storage;
     }
    public void run()
    {
     
     while(true)
     {
     try
      {
          Produce produce=new Produce((++produceName)+"");
          storage.Produce(produce);
        
        sleep(100);
       } 
       catch(InterruptedException ie)
       {
        ie.printStackTrace();
        break;
       }
     }
    }
}
/**
* The consumer uses threads to simulate consumer behavior.
*/
class Consumer extends Thread
{
private Storage storage;
  
    public Consumer(Storage storage,String name)
    {
     super(name);
     this.storage=storage;
   
    }
   
public void run()
    {
    Produce produce;
     while(true)
     {
     try
       {
       produce=storage.Consume();
     
      
         sleep(500);
       }
      catch(InterruptedException ie)
       {
        ie.printStackTrace();
        break;
       }
     }
    }
}
public class ProducerConsumer
{
public static void main(String[] args)
{
   Storage storage=new Storage(10);
   Producer producer1=new Producer(storage,"producer_01");
    Producer producer2=new Producer(storage,"producer_02");
   Consumer consumer1=new Consumer(storage,"consumer_01");
   Consumer consumer2=new Consumer(storage,"consumer_02");
   Consumer consumer3=new Consumer(storage,"consumer_03");
   Consumer consumer4=new Consumer(storage,"consumer_04");
   Consumer consumer5=new Consumer(storage,"consumer_05");
  producer1.start();
   producer2.start();
   consumer1.start();
   consumer2.start();
   consumer3.start();
   consumer4.start();
   consumer5.start();
 }
}

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.