Skip to content

Instantly share code, notes, and snippets.

@sontx
Last active March 29, 2016 15:35
Show Gist options
  • Save sontx/cf07306893de22399749 to your computer and use it in GitHub Desktop.
Save sontx/cf07306893de22399749 to your computer and use it in GitHub Desktop.
A simple demo for using wait() and notify() method in java to sync thread
public class Program {
static Object lock = new Object();
static class A implements Runnable {
@Override
public void run() {
synchronized (lock) {
System.out.println("I'm running in thread A");
System.out.println("Call wait() in thread A");
try {
lock.wait();
} catch (InterruptedException e) {
}
System.out.println("Notify called from another thread!");
System.out.println("Thread A is running...");
}
}
}
static class B implements Runnable {
@Override
public void run() {
System.out.println("I'm running in thread B");
System.out.println("Sleep 2s then notify for thread A...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
synchronized (lock) {
lock.notify();
}
System.out.println("Called notify");
}
}
public static void main(String[] args) {
new Thread(new A()).start();
new Thread(new B()).start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment