Best wait syntax in Java
I have an animation running in the background and I want to register a callback when it's done. The animation is not standard java animation - it is c animation accessed through jni (so let's assume it is just an Object type).
The animation does not have an onFinish method to register, but it does have an isDone () method that returns a boolean value if the animation no longer works. To create the callback, I added the executable as such:
class Foo implements Runnable {
@Override
public void run() {
if (animation == null || target == null) return;
while (!animation.isDone())
{
//loop until animation is done...
}
//execute callback
}
}
It looks like it would be a bad way to do it - just by running a loop until the animation ends. However, my question is, what are the alternative or preferred ways to wait for isDone () to return true in order to execute my callback?
source to share
If you cannot change the animation class use
while(!animation.isDone()){
Thread.sleep(SOME_TIME);
}
But if you can change the behavior of the animation, then at the end of the animation (when isDone start return true) add something like this:
synchronized(this){
this.notifyAll();
}
and instead in a loop you can use
synchronized(animation){
if(!animation.isDone){
animation.wait();
}
}
source to share