Skip to content

Instantly share code, notes, and snippets.

@MarounMaroun
Last active April 19, 2016 11:23
Show Gist options
  • Select an option

  • Save MarounMaroun/0bde7c92f1542b98ace2b9a1888478bc to your computer and use it in GitHub Desktop.

Select an option

Save MarounMaroun/0bde7c92f1542b98ace2b9a1888478bc to your computer and use it in GitHub Desktop.
public class Data {
private int data;
private boolean available = false;
synchronized public void put(int value) {
// there's already something in data
while (available) {
try {
wait();
} catch (InterruptedException e) { }
}
// nothing is available, should put something
// and notify all threads that're waiting to regain the lock
// and start execute their code again
available = true;
data = value;
notifyAll();
}
synchronized public int get() {
// there's nothing to get, go into a wait state until there'll be
// something to consume
while (!available) {
try {
wait();
} catch (InterruptedException e) { }
}
available = false;
notifyAll();
return data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment