Java solves a single buffered producer consumer problem example
- 2020-04-01 03:20:55
- OfStack
Classical producer - consumer problem simulation. This program simulates the simplest case - single buffering. In order to simulate the actual situation, delay is added when consume item and produce item, and different generation consumption rates can be simulated by modifying the delay.
[code]
[/ co
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 the run () {
/ / For (int I = 0; I< 10; I++) {
For (int I = 0; ; I++) {
/ / produce the item.
Try {
Thread.sleep (1000);
} catch (InterruptedException e) {
E.p rintStackTrace ();
}
String item = new String("item-" + I);
Println ("[producer] produced "+ item);
// wait for buffer empty.
Synchronized (condProducer) {
While (buffer! = null) {
Try {
CondProducer. Wait ();
} catch (InterruptedException e) {
E.p rintStackTrace ();
}
}
}
// put item to buffer.& cake;
Synchronized (mutex) {
Buffer = item;
System.out.println("[producer] put "+ item +" to buffer.");
}
/ / notify consumers.
Synchronized (condConsumer) {
CondConsumer. Notify ();
}
}
}
};
Thread consumer = new Thread() {
Public void the 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.p rintStackTrace ();
}
}
}
// get item from buffer.
String item = null;
Synchronized (mutex) {
The item = (String) buffer;
Buffer = null;
System. Out.println (" [consumer] get "+ item +" from buffer.");
}
/ / consume item.
Try {
Thread.sleep (500);
} catch (InterruptedException e) {
E.p rintStackTrace ();
}
System. Out.println (" [consumer] comsumed "+ item);
/ / notify producers.
Synchronized (condProducer) {
CondProducer. Notify ();
}
}
}
};
Consumer. The start ();
Producer. The start ();
}
} DE]