开发者

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

开发者 https://www.devze.com 2023-04-12 02:33 出处:网络
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 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

精彩评论

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