Skip to content

Instantly share code, notes, and snippets.

@hackjutsu
Last active February 28, 2018 10:17
Show Gist options
  • Save hackjutsu/13eb729aae791ee83cad698b6b8ad18c to your computer and use it in GitHub Desktop.
Save hackjutsu/13eb729aae791ee83cad698b6b8ad18c to your computer and use it in GitHub Desktop.
[wait/notify/notifyAll] Example for Java Object's wait/notify/notifyAll #concurrency mechanism.
public class ObjectWaitNotifyExample {
private static final long SLEEP_INTERVAL_MS = 1000;
private boolean running = true;
private Thread thread;
public void start() {
print("Inside start()...");
thread = new Thread(new Runnable() {
@Override
public void run() {
print("Inside run()...");
try {
Thread.sleep(SLEEP_INTERVAL_MS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
synchronized (ObjectWaitNotifyExample.this) {
running = false;
ObjectWaitNotifyExample.this.notify();
}
}
});
thread.start();
}
public void join() throws InterruptedException {
print("Inside join()...");
synchronized (this) {
while (running) {
print("Waiting for the peer thread to finish.");
wait();//waiting, not running
}
print("Peer thread finished.");
}
}
private void print(String s) {
System.out.println(s);
}
public static void main(String[] args) throws InterruptedException {
ObjectWaitNotifyExample cve = new ObjectWaitNotifyExample();
cve.start();
cve.join();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment