Search code examples
javamultithreadingfire-and-forget

Java "Fire and Forget" Thread


I have a method

public static void startAnimation() {
    new AnimationThread().run();
}

where AnimationThread implements runnable and its constructor is:

public AnimationThread() {
    new Thread(this, "Animation Thread");
    EventQueue.setAnimationCounter(0);
    alive = true;
}

which i am calling from the init() method of an applet hangs as it never returns a value. Is there a way to start this thread and get the init() method to finish so that my applet will start!

Thanks


Solution

  • You need to move things around a bit:

    public AnimationThread() {
       EventQueue.setAnimationCounter(0);
       alive = true;
       new Thread(this, "Animation Thread").start();
    }
    
    public static void startAnimation() {
       new AnimationThread();
    }
    

    start() is the magic Thread method that runs code on a different thread; the AnimationThread constructor will return normally after calling it, the AnimationThread.run() will execute in a new thread.