I have just written a simple java example to get familiar with the concept of wait and notify methods.
The idea is that when calling notify()
, the main thread will print the sum.
MyThread class
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 I got 10 instead.
Well, what I though is that when notify()
is called, the main thread will wakeup and execute the System.out.println(t.times)
which should give 5. Then the run()
will continue till it finishes the for loop which will update the value of times to 10.
Any help is highly appreciated.