Last active
October 7, 2018 14:13
-
-
Save sadegh/8f0c6959d8b86508c3d6319dafd69f72 to your computer and use it in GitHub Desktop.
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
package com.skazemy; | |
import java.util.ArrayList; | |
import java.util.List; | |
/** | |
* This example shows that after calling wait() on an object, it will release that object's monitor lock, | |
* so that other threads can enter the synchronized block. It also shows once notifyAll() | |
* is called, first that thread has to exit the synchronized block, then each waiting thread starts | |
* doing their work one by one, each has to exit their synchronized block so the other can wake up | |
*/ | |
public class Main { | |
public static void main(String[] args) { | |
final Object object = new Object(); | |
class Waiter implements Runnable { | |
@Override | |
public void run() { | |
String thread = Thread.currentThread().getName(); | |
System.out.println(thread + " - Before sync"); | |
synchronized (object) { | |
try { | |
System.out.println(thread + " - Before Wait"); | |
object.wait(); | |
System.out.println(thread + " Wait is done"); | |
Thread.sleep(2000); | |
System.out.println(thread + " Sleep is Done"); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
System.out.println(thread + " Wait is done After sync"); | |
} | |
} | |
List<Thread> threads = new ArrayList<>(10); | |
for (int i = 0 ; i < 10 ; i++) { | |
threads.add(new Thread(new Waiter(), "thread " + i)); | |
} | |
Thread thread3 = new Thread(new Runnable() { | |
@Override | |
public void run() { | |
try { | |
Thread.sleep(5000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
System.out.println("Notifier - Before sync"); | |
synchronized (object) { | |
System.out.println("Notifier - Before notify"); | |
object.notifyAll(); | |
System.out.println("Notify is done"); | |
System.out.println("Notifier sleeps again"); | |
try { | |
Thread.sleep(5000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
System.out.println("Notifier wakes up"); | |
} | |
} | |
}); | |
for (Thread thread: threads) { | |
thread.start(); | |
} | |
thread3.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment