Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.denis.learning.multithreading;
- public class WaitNotifyExample {
- private static final Object monitor = new Object();
- private static Integer i = null;
- public static void main(String[] args) {
- new Thread(() -> {
- while (true) {
- try {
- synchronized (monitor) {
- while (i == null) {
- monitor.wait();
- }
- System.out.println(i);
- i = null;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }).start();
- new Thread(() -> {
- for (int j = 0; j < 100; j++) {
- try {
- synchronized (monitor) {
- Thread.sleep(1000);
- i = j;
- monitor.notifyAll();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }).start();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment