Skip to content

Instantly share code, notes, and snippets.

@MichaelScofield
Created May 7, 2013 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelScofield/5532066 to your computer and use it in GitHub Desktop.
Save MichaelScofield/5532066 to your computer and use it in GitHub Desktop.
Typical usage of Object.wait() and Object.notify()
package test;
public class Main {
private final Object MONITOR = new Object();
private class PrintNum extends Thread {
volatile int num = 1;
@Override
public void run() {
while (true) {
synchronized (MONITOR) {
for (int i = 0; i < 2; i++) {
System.out.print(num++);
}
MONITOR.notifyAll();
if (num > 52) {
return;
}
try {
MONITOR.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
private class PrintWord extends Thread {
volatile char word = 'A';
@Override
public void run() {
while (true) {
synchronized (MONITOR) {
System.out.println(word++);
MONITOR.notifyAll();
if (word > 'Z') {
return;
}
try {
MONITOR.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public void test() throws InterruptedException {
PrintNum printNum = new PrintNum();
PrintWord printWord = new PrintWord();
printNum.start();
Thread.sleep(100);
printWord.start();
}
public static void main(String[] args) throws InterruptedException {
new Main().test();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment