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 {
    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

3 answers

Basically, if you have no control over the Animation class, and it only exposes the isDone () method, the only way is with what you did (but with Thread.sleep for a specific amount of time, like 10 or 50ms).

Otherwise, you can organize it using one of the following methods:



If you cannot change the animation class use



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:



and instead in a loop you can use





You can use a subscription template. You must register a callback with the animation so that when the animation ends, it will execute your callback.

Another option could be to use Futures if your animations are inside executables or callers.



All Articles