Recently learning Java multithreading a little confused, after a day of finishing, know what is the producer, what is the consumer, as well as the relationship between consumers and producers:
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/6C/7E/wKiom1VKLYzRB5F-AAC5bQtmq-I129.jpg "title=" Producer consumer schematic. png "alt=" wkiom1vklyzrb5f-aac5bqtmq-i129.jpg "/>
In the person class is an entity does not have a specific object, by input, output readout, only if input has passed in, can be output read, so yes input and output, to the same lock, synchronized two threads synchronization.
Wait (), notify (), Notifyall () are all inherited to the God class: The following is the code of the producer consumer
//Production/consumer mode
Public class Basket {
Lock lock = new reentrantlock ();
//Generate Condition Object
Condition produced = Lock.newcondition ();
Condition consumed = Lock.newcondition ();
Boolean available = false;
Public void Produce () throws interruptedexception {
Lock.lock ();
Try {
if (available) {
Produced.await (); //Discard lock into sleep
}
System.out.println (" Apple produced.");
Available = true;
Consumed.signal (); //Signal wakeup wait for this condition thread
} finally {
Lock.unlock ();
}
}
Public void consume () throws interruptedexception {
Lock.lock ();
Try {
if (!available) {
Consumed.await (); //Discard lock into sleep
}
/ * Eat apples * /
System.out.println (" Apple consumed.");
Available = false;
Produced.signal (); //Signal wakeup wait for this condition thread
} finally {
Lock.unlock ();
}
}
}
This article from "Javase and Android" blog, declined reprint!
Primary discussion of Java producers and consumers