Skip to content

Instantly share code, notes, and snippets.

@ansig
Created November 9, 2014 19:14
Show Gist options
  • Save ansig/057e59bbcc7f9f836254 to your computer and use it in GitHub Desktop.
Save ansig/057e59bbcc7f9f836254 to your computer and use it in GitHub Desktop.
Classes that produce and consume data from a shared store to demonstrate the wait/notify mechanism.
import java.util.ArrayList;
/**
* Classes that produce and consume data from a shared store to demonstrate the wait/notify mechanism.
*/
public class WaitNotifyMechanism {
static ArrayList<Integer> dataStore = new ArrayList<Integer>();
static class Producer extends Thread {
public Producer(String name) {
this.setName(name);
}
public void run() {
while (true) {
synchronized (dataStore) {
while (!dataStore.isEmpty()) {
System.out.printf("%s waiting for data to be empty...%n", this.getName());
try {
dataStore.wait();
} catch (InterruptedException ie) {
System.out.printf("%s interrupted while waiting!%n", this.getName());
}
}
System.out.printf("%s producing data...%n", this.getName());
try {
sleep(5000);
} catch (InterruptedException ie) {
System.out.printf("%s interrupted while producing data!%n", this.getName());
}
Integer newData = new Integer((int) (Math.random()*5000));
System.out.printf("%s produced: %d%n", this.getName(), newData);
dataStore.add(newData);
dataStore.notifyAll();
System.out.printf("%s done!%n", this.getName());
}
}
}
}
static class Consumer extends Thread {
public Consumer(String name) {
this.setName(name);
}
public void run() {
while(true) {
synchronized (dataStore) {
while (dataStore.isEmpty()) {
System.out.printf("%s waiting for data...%n", this.getName());
try {
dataStore.wait();
} catch (InterruptedException ie) {
System.out.printf("%s interrupted while waiting!%n", this.getName());
}
}
System.out.printf("%s consuming data...%n", this.getName());
try {
sleep(5000);
} catch (InterruptedException ie) {
System.out.printf("%s interrupted while producing data!%n", this.getName());
}
Integer theData = dataStore.remove(0);
System.out.printf("%s got: %d%n", this.getName(), theData);
dataStore.notifyAll();
System.out.printf("%s done!%n", this.getName());
}
}
}
}
public static void main(String[] args) {
new Consumer("Cons1").start();
new Consumer("Cons2").start();
new Producer("Prod1").start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment