Copy Code code as follows:
Package condition;
Import java.util.ArrayList;
Import java.util.List;
Import java.util.concurrent.locks.Condition;
Import Java.util.concurrent.locks.Lock;
Import Java.util.concurrent.locks.ReentrantLock;
/**
* Using lock and condition to realize producer consumer model
* @author would
*
*/
public class Producerconsumerdemo {
public static void Main (string[] args) {
int producercount = 10;
int consumercount = 15;
Final Producerconsumerdemo PCD = new Producerconsumerdemo (5); Buffer size is 5
thread[] producerthreads = new Thread[producercount];
for (int i = 0; i < Producercount; i++) {
Producerthreads[i] = new Thread ("producer" + (i+1)) {
@Override
public void Run () {
Pcd.produce ();
}
};
}
thread[] consumerthreads = new Thread[consumercount];
for (int j = 0; J < Consumercount; J + +) {
CONSUMERTHREADS[J] = new Thread ("Consumer" + (j+1)) {
@Override
public void Run () {
Pcd.consume ();
}
};
}
Start producer Consumer Thread
for (int i = 0; i < Producercount; i++) {
Producerthreads[i].start ();
}
for (int j = 0; J < Consumercount; J + +) {
Consumerthreads[j].start ();
}
}
private static final int default_buffer_size = 10;
private int buffersize; Buffer size
Private list<object> bufferlist;
Private Final lock lock = new Reentrantlock (true);
Private final Condition Condition = Lock.newcondition ();
Public Producerconsumerdemo (int buffersize) {
this.buffersize = buffersize > 0? Buffersize:default_buffer_size;
Bufferlist = new arraylist<object> (buffersize);
}
Production
public void produce () {
Lock.lock (); Lock
try {
while (bufferlist.size () = = buffersize) {//Buffer full
System.out.println ("Producer Wait, Thread:" + thread.currentthread (). GetName ());
Condition.await ();
}
Production
Bufferlist.add (New Object ());
System.out.println ("Producer produce one, now buffer size:"
+ bufferlist.size () + ", and Thread:" + thread.currentthread (). GetName ());
Condition.signalall (); Inform consumers
catch (Interruptedexception e) {
E.printstacktrace ();
finally {
Lock.unlock ();
}
}
Consumption
public void consume () {
Lock.lock (); Lock
try {
while (Bufferlist.isempty ()) {//Buffer empty
System.out.println ("Consumer Wait, Thread:" + thread.currentthread (). GetName ());
Condition.await ();
}
Consumption
Bufferlist.remove (0); Remove one from the head of the list
System.out.println ("Consumer Consumer one, now buffer size:"
+ bufferlist.size () + ", and Thread:" + thread.currentthread (). GetName ());
Condition.signalall ();
catch (Interruptedexception e) {
E.printstacktrace ();
finally {
Lock.unlock ();
}
}
}