Skip to content

Instantly share code, notes, and snippets.

@lobster1234
Created April 19, 2019 04:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lobster1234/f90a355a745f8600e64557401cec384f to your computer and use it in GitHub Desktop.
Save lobster1234/f90a355a745f8600e64557401cec384f to your computer and use it in GitHub Desktop.
Producer Consumer with wait/notify
package org.lobster1234;
import java.util.Random;
import java.util.Stack;
/**
* Simple demo of producer-consumer problem with wait and notify
*
*/
public class ProducerConsumer {
private Stack<Integer> stack = new Stack<>();
private Object lock = new Object();
private int MAX_SIZE = 10;
/**
* Push a random number on the stack. If the stack is full, then just wait.
* @throws Exception
*/
public void produce() throws Exception{
while(true) {
synchronized (lock) {
while(stack.size()==MAX_SIZE) {
System.out.println("Full, waiting..");
lock.wait();
}
int number = new Random().nextInt(100);
stack.push(number);
System.out.println("Producer pushed " + number);
lock.notify();
}
}
}
/**
* Consume or pop an item from the stack. If the stack is empty, then wait
* @throws Exception
*/
public void consume() throws Exception{
while(true){
synchronized (lock) {
while(stack.isEmpty()){
System.out.println("Empty, waiting..");
lock.wait();
}
System.out.println("Consumer pulled " + stack.pop());
lock.notify();
}
Thread.sleep(500); //we add this so the producer can fill the stack
}
}
public static void main(String[] args) throws Exception{
ProducerConsumer producerConsumer = new ProducerConsumer();
Thread producer = new Thread(()-> {try{producerConsumer.produce();}catch(Exception e){}});
Thread consumer = new Thread(()-> {try{producerConsumer.consume();}catch(Exception e){}});
producer.start();
consumer.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment