Java producers and consumers

Source: Internet
Author: User
Tags stub

Examples of producers and consumers

First, Wait ()/notify () Method

The wait ()/nofity () method is the two method of the base class object, which means that all Java classes will have both methods, so that we can implement synchronization mechanisms for any object.

Wait () method: When the buffer is full/empty, the producer/consumer thread stops its own execution, discards the lock, keeps itself in the state, and lets other threads execute it.

Notify () method: When a producer/consumer puts a product into a buffer, it sends an executable notification to the other waiting thread while discarding the lock, leaving itself in a wait state.

Put the code directly with AS

Class person{
Private String name;
Private String sex;

Private Boolean isEmpty = boolean.true;

public void set (String name,string sex) {
synchronized (this) {
while (!isempty.equals (boolean.true)) {
try {
this.wait ();
} catch (Interruptedexception e) {
//TODO auto-generated catch block
E.printstacktrace ( );
}
}
This.name=name;
try {
Thread.Sleep (1);
} catch (Interruptedexception e) {
//TODO auto-generated catch block
E.printstacktrace ();
}
This.sex=sex;
Isempty=boolean.false;
This.notifyall ();
}
}

public void Get () {
synchronized (this) {
while (!isempty.equals (Boolean.false)) {
try {
This.wait ();
} catch (Interruptedexception e) {
//TODO auto-generated catch block
E.printstacktrace ();
}
}
String name=getname ();
String Sex=getsex ();
System.out.println (name + "-+" + sex);
Isempty=boolean.true;
This.notifyall ();
}
}

Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
Public String Getsex () {
return sex;
}
public void Setsex (String sex) {
This.sex = sex;
}

}

Class Producer implements runnable{
private person p;
Public Producer (person p) {
This.p=p;

}

@Override
public void Run () {
TODO auto-generated Method Stub
for (int i=2;i<100;i++) {
if (i%2==0) {
P.set ("Li Guo", "female");
}else{
P.set ("Li fan", "male");
}
}
}

}
Class Consumer implements runnable{
private person p;
Public Consumer (person p) {
This.p=p;
}
@Override
public void Run () {
TODO auto-generated Method Stub
for (int i=2;i<100;i++) {
P.get ();
}
}

}
public class Productor_consumerdemo {

public static void Main (string[] args) {
TODO auto-generated Method Stub
Person p = new person ();
New Thread (New Producer (p)). Start ();
New Thread (New Consumer (p)). Start ();

New Thread (New Producer (p)). Start ();
New Thread (New Consumer (p)). Start ();
}

}

Synchronous method with synchronized

await ()/signal () Method

After JDK5.0, Java provides a more robust threading mechanism, including synchronization, locking, thread pooling, and so on, which enables finer-grained threading control. await () and signal () are the two methods used to do synchronization, their functions are basically the same as wait ()/nofity (), but they can completely replace them, but they are directly linked with the newly introduced locking mechanism lock, with greater flexibility. By invoking the Newcondition () method on the lock object, the condition variable is bound to a lock object, which in turn controls the security of the concurrent program's access to the competing resource. Here's a look at the code:

Class Person {
private String name;

Public String GetName () {
return name;
}

public void SetName (String name) {
THIS.name = name;
}

Public String Getsex () {
return sex;
}

public void Setsex (String sex) {
This.sex = sex;
}

Private String sex;

Private final Reentrantlock lock = new Reentrantlock ();
Private final Condition con = lock.newcondition ();
Private Boolean isEmpty = boolean.true;

public void Set (string name, string sex) {
Lock.lock ();
while (!isempty.equals (boolean.true)) {
try {
Con.await ();
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}

try {
THIS.name = name;
Thread.Sleep (1);
This.sex = sex;
IsEmpty = Boolean.false;
Con.signal ();
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
} finally {
Lock.unlock ();
}

}

public void get () {
Lock.lock ();
while (!isempty.equals (Boolean.false)) {
try {
Con.await ();
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}

try {
String name = GetName ();

String sex = Getsex ();
SYSTEM.OUT.PRINTLN (name +--+ + sex);
IsEmpty = Boolean.true;
Con.signal ();

} finally {
Lock.unlock ();
}
}
}

Class Productor implements Runnable {
private person p;

Public productor (person p) {
THIS.P = p;
}

@Override
public void Run () {
TODO auto-generated Method Stub
for (int i = 2; i <; i++) {
if (i% 2 = = 0) {
P.set ("Li Guo", "female");
} else {
P.set ("Li Yu Xuan", "male");
}
}
}

}

Class Cosumer implements Runnable {
private person p;

Public Cosumer (person p) {
THIS.P = p;
}

@Override
public void Run () {
TODO auto-generated Method Stub
for (int i = 2; i <; i++) {
P.get ();
}

}

}

public class Producer_demo {

public static void Main (string[] args) {
TODO auto-generated Method Stub
Person p = new person ();

New Thread (New Productor (p)). Start ();
New Thread (New Cosumer (p)). Start ();
}

}

Java producers and consumers

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.