Skip to content

Instantly share code, notes, and snippets.

@tsujeeth
Created June 17, 2016 01:08
Show Gist options
  • Save tsujeeth/ca4546d36924f0c121326bf5b3a485ae to your computer and use it in GitHub Desktop.
Save tsujeeth/ca4546d36924f0c121326bf5b3a485ae to your computer and use it in GitHub Desktop.
Example of Wait-Notify synchronization in Java
class Bottle {
private String message;
Bottle() {
message = "";
}
public synchronized void set(String message) {
this.message = message;
notifyAll();
}
public synchronized String get() {
while (message.length() == 0) {
try {
wait();
}
catch (InterruptedException exception) {}
}
return message;
}
}
class Producer implements Runnable {
private Bottle bottle;
Producer(Bottle bottle) {
this.bottle = bottle;
}
public void run() {
try {
Thread.sleep(5000);
bottle.set("hello");
}
catch (InterruptedException exception) {}
}
}
class Consumer implements Runnable {
private Bottle bottle;
Consumer(Bottle bottle) {
this.bottle = bottle;
}
public void run() {
String message = bottle.get();
System.out.format("Message in the bottle: %s %n", message);
}
}
public class MessageWaiterDemo {
public static void main(String[] args) {
Bottle bottle = new Bottle();
Thread producer = new Thread(new Producer(bottle));
Thread consumer = new Thread(new Consumer(bottle));
producer.start();
consumer.start();
try {
producer.join();
consumer.join();
}
catch (InterruptedException exception) {
exception.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment