Last active
February 28, 2018 10:17
-
-
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.
This file contains hidden or 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 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