Created
March 6, 2013 08:05
-
-
Save lobster1234/5097545 to your computer and use it in GitHub Desktop.
A very simple wait/notify example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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