I have created an java thread and passed an stack reference to it\'s constructor, which initialize thread stack reference. In run method i have created an synchronized block
For wait() (or notify()) to work, you must call it on the same object. What you have now is the same as
synchronized (stack) {
if(stack.isEmpty()){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
instead you should do
synchronized (stack) {
if(stack.isEmpty()){
try {
stack.wait(); // wait on the same object synchronized.
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Note: as wait can wake spuriously you have do this in a loop or your method could return prematurely.
synchronized (stack) {
while (stack.isEmpty()){
try {
stack.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}