Skip to content
Advertisement

I was searching for stopping java thread gracefully and found that, but I cannot know how to check example of this situation

This is good example of stopping thread. How to stop a java thread gracefully?
But when I try to check this example I received infinite loop.

This is my code:

public class Num {

    public void crash(ManualStopping t1) {
        t1.stopMe();
    }

    public static void main(String[] args) {

        Num num = new Num();
        ManualStopping t1 = new ManualStopping();
        t1.run();
        System.out.println("Main thread");
        num.crash(t1);
    }
}
class ManualStopping extends Thread {

    volatile boolean finished = false;
    public void stopMe() {
        finished = true;
    }
    public void run() {
        while (!finished) {
            System.out.println("I'm alive");
        }
    }
}

Advertisement

Answer

I think you need to start your thread – not run it. By calling run, you are just making a normal method call, not running a separate thread.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement