开发者

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() {
        fin开发者_JS百科ished = true;
    }
    public void run() {
        while (!finished) {
            System.out.println("I'm alive");
        }
    }
}


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜