0

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");
        }
    }
}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
dwz
  • 377
  • 1
  • 3
  • 13
  • Good lesson for me: run() method does not create new thread it just execute run method. For creating new thread you should invoke start() method on a Thread instance Thanks for all) – dwz Oct 10 '11 at 09:33

3 Answers3

5

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.

DaveH
  • 7,187
  • 5
  • 32
  • 53
1

Nothing in your code calls the stopMe method on ManualStopping. isInterrupted() is a test that doesn't change the state of the thread. And as @DaveHowes points out, you don't even start a separate thread.

Adrian Cox
  • 6,204
  • 5
  • 41
  • 68
1

t1.run(); Change it to t1.start().

Whats happening is that the thread you intend to spawn is not actually running as a separate thread. Instead the loop

while(!finished){ System.out.println("I'm alive"); }

is running on the main thread and your code num.crash(t1); never actually gets invoked. This is causing the infinite loop.

Bhaskar
  • 7,443
  • 5
  • 39
  • 51