Denisnn

WaitNotifyExample

Jan 5th, 2018
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. package com.denis.learning.multithreading;
  2.  
  3. public class WaitNotifyExample {
  4. private static final Object monitor = new Object();
  5. private static Integer i = null;
  6.  
  7. public static void main(String[] args) {
  8. new Thread(() -> {
  9. while (true) {
  10. try {
  11. synchronized (monitor) {
  12. while (i == null) {
  13. monitor.wait();
  14. }
  15. System.out.println(i);
  16. i = null;
  17. }
  18. } catch (Exception e) {
  19. e.printStackTrace();
  20. }
  21. }
  22. }).start();
  23.  
  24. new Thread(() -> {
  25. for (int j = 0; j < 100; j++) {
  26. try {
  27. synchronized (monitor) {
  28. Thread.sleep(1000);
  29. i = j;
  30. monitor.notifyAll();
  31. }
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. }).start();
  37. }
  38.  
  39. }
Advertisement
Add Comment
Please, Sign In to add comment