Producer and consumer of Java thread communication

Source: Internet
Author: User

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

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.