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