I'm making a program with while loops that execute in this manner:
Here is an example:
while(path != null);
There's another function in the class that will set the path to null, and once that happens the main thread should exit this loop. The other function is called in another thread.
However, the main thread does not exit the loop even when path is set to null. Any suggestions?
CODE:
try
{
for (Node n:realpath)
{
Thread.sleep(100);
actor.walk(n);
}
Thread.sleep(100);
}
catch (InterruptedException ex)
{
Logger.getLogger(VNScreen.class.getName()).log(Level.SEVERE, null, ex);
}
realpath.clear();
path = null;
if(path == null)
System.out.println("NULLED PATH");
Busy waits are very expensive. I'd do it this way:
Object LOCK = new Object(); // just something to lock on
synchronized (LOCK) {
while (path != null) {
try { LOCK.wait(); }
catch (InterruptedException e) {
// treat interrupt as exit request
break;
}
}
}
Then when you set path
to null, just call
synchronized (LOCK) {
LOCK.notifyAll();
}
(You can just synchronize on this
if both pieces of code are in the same object.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With