Last active
March 29, 2016 15:35
-
-
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
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
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