I am studying Threads Java and its features and I came across a question.
I have the following classes in my program:
public class Main {
public static void main(String[] args) {
ThreadB b = new ThreadB();
b.start();
synchronized (b) {
try {
System.out.println("Waiting for complete b...");
b.wait();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Total: " + b.total);
}
}
}
ThreadB
:
public class ThreadB extends Thread {
int total;
@Override
public void run() {
synchronized (this) {
for (int i = 0; i < 200; i++) {
total += i;
}
notify(); //notifyAll();
while(true) {
//Do something
}
}
}
}
Running this program I can not get the expected behavior of the notify()
command when I add the code snippet below in ThreadB
:
while(true) {
//Do something
}
See outputs with and without the quoted passage
WillIhavetowaittofinishThreadB
sameMain
beingnotifiedthatthetotalisalreadycalculated?
IsthereanythingthatcanbedonetogettotalwithoutThreadB
ending?
Beforearrivinghere,Icheckedthis question with a similar subject from another user.