Package cn.test.hf.test3;
Import java.util.concurrent.locks.Condition;
Import Java.util.concurrent.locks.ReentrantLock;
public class Factoryutils {
Private Resource Resource;
private int producerid = 1;
Can be re-entered lock
Reentrantlock lock = new Reentrantlock ();
Condition producerscondition = Lock.newcondition ();
Condition customerlockcondition = Lock.newcondition ();
Factoryutils () {
Resource = new resource ();
Resource.setid (0);
Resource.setflag (TRUE);
}
/**
* Production
*/
public void Producerresource () {
Lock.lock ();
Using the lock mechanism
try {
while (true) {
while (!resource.isflag ()) {
Not yet consumed, the thread waits
System.out.println ("producer Wait");
Use condition to notify the same group of Waits
Producerscondition.await ();
}
Production
Resource.setid (producerid++);
Resource.setflag (FALSE);
System.out.println ("producer Threads" + Thread.CurrentThread (). GetName () + "production of products with ID" + resource.getid () + ");
Delay one second good-looking results
Thread.Sleep (1000);
Notify consumer thread when finished production
SYSTEM.OUT.PRINTLN ("notifying consumers");
Customerlockcondition.signalall ();
}
} catch (Exception e) {
E.printstacktrace ();
} finally {
Release lock
Lock.unlock ();
}
}
/**
* Production
*/
Public synchronized void customer () {
Lock.lock ();
try {
while (true) {
Consumer Waiting
while (Resource.isflag ()) {
Customerlockcondition.await ();
}
Set to Consumed
Resource.setflag (TRUE);
SYSTEM.OUT.PRINTLN ("Consumer thread" + thread.currentthread (). GetName () + "consumption of products with ID" + resource.getid () + ");
Delay one second good-looking results
Thread.Sleep (1000);
Notify producer of thread production after consumption is finished
System.out.println ("notify producer");
Producerscondition.signalall ();
}
} catch (Exception e) {
E.printstacktrace ();
} finally {
Lock.unlock ();
}
}
}
Producer and consumer of Java thread communication