Created
May 7, 2013 12:01
-
-
Save MichaelScofield/5532066 to your computer and use it in GitHub Desktop.
Typical usage of Object.wait() and Object.notify()
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
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