Skip to content

Instantly share code, notes, and snippets.

@lobster1234
Created March 6, 2013 08:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lobster1234/5097545 to your computer and use it in GitHub Desktop.
Save lobster1234/5097545 to your computer and use it in GitHub Desktop.
A very simple wait/notify example
public class WaitNotifyExample {
public static void main(String[] args) {
Integer lock = new Integer(0);
Thread waiter = new Thread(new Waiter(lock));
waiter.start();
Thread notifier = new Thread(new Notifier(lock));
notifier.start();
}
}
class Waiter implements Runnable {
public Integer lock;
public Waiter(Integer lock) {
this.lock = lock;
}
public void run() {
synchronized (lock) {
try {
System.out.println("Waiter is now waiting on the lock");
lock.wait();
System.out.println("Waiter just got notified!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Notifier implements Runnable {
public Integer lock;
public Notifier(Integer lock) {
this.lock = lock;
}
public void run() {
synchronized (lock) {
try {
// sleep!
Thread.sleep(1000);
System.out.println("About to notify the waiter..");
lock.notify();
System.out.println("Done notifying the waiter.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment