Created
July 23, 2015 13:01
-
-
Save ivanursul/dd839a8785d45e935e5d 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
| 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