The classic producer consumer problem simulation. This program simulates the simplest case-single buffering. In order to simulate the actual situation, the consume item and the produce item were added with the delay, and the different generation consumption rate could be simulated by modifying the delay.
[Code]
[/co/**
* Single buffer consumer-producer problem.
* by Xu (xusiwei1236@163.com).
* */
public class Consumerproducer {
static Object buffer = NULL;
Static Object Mutex = new Object ();
static Object Condconsumer = new Object ();
static Object Condproducer = new Object ();
public static void Main (string[] args) {
Thread producer = new Thread () {
public void Run () {
for (int i=0; i<10; i++) {
for (int i=0; i++) {
Produce item.
try {
Thread.Sleep (1000);
catch (Interruptedexception e) {
E.printstacktrace ();
}
String item = new String ("item-" + i);
System.out.println ("[producer] produced" + item);
Wait for buffer empty.
Synchronized (condproducer) {
while (buffer!= null) {
try {
Condproducer.wait ();
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
Put the item to buffer.
Synchronized (mutex) {
Buffer = Item;
System.out.println ("[producer] put" + Item + "to buffer.");
}
Notify consumers.
Synchronized (Condconsumer) {
Condconsumer.notify ();
}
}
}
};
Thread consumer = new Thread () {
public void Run () {
for (int i=0; i<10; i++) {
for (;;) {
Wait for item come.
Synchronized (Condconsumer) {
while (buffer = null) {
try {
Condconsumer.wait ();
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
Get item from buffer.
String item = NULL;
Synchronized (mutex) {
Item = (String) buffer;
buffer = NULL;
System.out.println ("[Consumer] get" + Item + "from buffer.");
}
Consume item.
try {
Thread.Sleep (500);
catch (Interruptedexception e) {
E.printstacktrace ();
}
System.out.println ("[Consumer] comsumed" + item);
Notify producers.
Synchronized (condproducer) {
Condproducer.notify ();
}
}
}
};
Consumer.start ();
Producer.start ();
}
}de]