Skip to content

Instantly share code, notes, and snippets.

@ivanursul
Created July 23, 2015 13:01
Show Gist options
  • Select an option

  • Save ivanursul/dd839a8785d45e935e5d to your computer and use it in GitHub Desktop.

Select an option

Save ivanursul/dd839a8785d45e935e5d to your computer and use it in GitHub Desktop.
public class Main {
private Object lock = new Object();
public void doWait(){
synchronized(lock){
try{
System.out.println("Start waiting");
lock.wait();
System.out.println("End waiting");
} catch(InterruptedException e){
e.printStackTrace();
}
}
}
public void methodBeforeEndWaiting() {
synchronized (lock) {
System.out.println("Method before 'End Waiting' will be printed");
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void doNotify(){
synchronized(lock){
System.out.println("Start notifying");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
methodBeforeEndWaiting();
}
});
thread.start();
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.notify();
System.out.println("End notifying");
}
}
public static void main(String[] args) throws InterruptedException {
Main main = new Main();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
main.doWait();
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
main.doNotify();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment