Java multi-producer multi-consumer example

Source: Internet
Author: User

Import java.util.concurrent.locks.*;


public class Test9 {

public static void Main (string[] args) {
TODO auto-generated method stubs
Resource r=new Resource ();
Producer p=new Producer (R);
Consumer c=new Consumer (R);
Thread t0=new thread (p);
Thread t1=new thread (p);
Thread t2=new thread (c);
Thread t3=new thread (c);
T0.start ();
T1.start ();
T2.start ();
T3.start ();
}

}

Class Resource
{
private String name;
private int count=1;
Private Boolean flag;

Creates a lock object.
Lock lock;
Get two sets of monitor objects through an existing lock, a group of monitoring producers, and a group of monitoring consumers.
Condition Producer_con;
Condition Consumer_con;
Public Resource ()
{
this.lock= new Reentrantlock ();
This.producer_con = Lock.newcondition ();
This.consumer_con = Lock.newcondition ();
}

Public void Set (String name)
{
Lock.lock ();
try {
While (flag)
producer_con.await ();
This.name=name+count;
count++;
System.out.println (Thread.CurrentThread (). GetName () + ".... Producer ... "+this.name);
flag=true;
consumer_con.signal ();
} catch (Interruptedexception e) {
//TODO auto-generated catch block
e.printstacktrace ();
}finally{
Lock.unlock ();
}
}
Public Void Get ()
{
Lock.lock ();
try {
While (!flag)
consumer_con.await ();
System.out.println (Thread.CurrentThread (). GetName () + ".... Consumers ... "+this.name);
Flag=false;
producer_con.signal ();
} catch (Interruptedexception e) {
//TODO auto-generated catch block
e.printstacktrace ();
}finally{
Lock.unlock ();
}

}
}
class Producer implements Runnable
{

Resource R=null;
Public Producer (Resource R)
{
This.r=r;
}
public void Run () {
TODO auto-generated method stubs
while (true)
R.set ("Roast duck");
}

}

Class Consumer implements Runnable
{

Resource R=null;
Public Consumer (Resource R)
{
This.r=r;
}
public void Run () {
TODO auto-generated method stubs
while (true)
R.get ();
}
}

Java multi-producer multi-consumer example

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.