Java call notify () in if condition

I just wrote a simple java example to familiarize myself with the concept of wait and notification methods.

The idea is that when called, the notify()main thread will print the sum.

Class mythread

public class MyThread extends Thread {
    public int times = 0;

    @Override
    public void run() {

        synchronized (this) {
            try {
                for (int i = 0; i < 10; i++) {
                    times += 1;
                    Thread.sleep(500);
                    if (i == 5) {
                        this.notify();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Main class

public class Main {

    public static void main(String[] args) {

        MyThread t = new MyThread();
        synchronized (t) {
            t.start();
            try {
                t.wait();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(t.times);
        }
    }
}

Expected results

5, but instead I got 10.

Well, although I know that when called, the notify()main thread will start and run System.out.println(t.times), which should give 5. Then it run()will continue until it completes the for loop, which updates the time value to 10.

Any help is appreciated.

+4
source share
1 answer

. . , .

, , , MyThread, , . , :

  • .
  • .
  • , , .
  • wait(). WAITING.
  • .
  • notify(). , , , .
  • , , ( ). , , , , .
  • , times 10 , , , .
  • println. times 10.

join() , , ndash; , .

, , 5, :

public class MyThread extends Thread {
    public volatile int times = 0;

    @Override
    public void run() {
        try {
            for (int i = 0; i < 10; i++) {
                times += 1;
                Thread.sleep(500);
                if (i == 5) {
                    synchronized(this) {
                        this.notify();
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

times volatile, JVM , .

, , 5. , println , - , 5 ( - sleep() ).

+5

Source: https://habr.com/ru/post/1654195/


All Articles