我正在寻找优雅地停止 java 线程并发现了这一点,但我不知道如何检查这种情况的示例
这是停止线程的好例子。 如何优雅地停止 java 线程?
但是当我尝试检查这个示例时,我收到了无限循环。
这是我的代码:
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");
}
}
}
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");
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您需要
启动
您的线程 - 而不是运行
它。通过调用 run,您只是进行正常的方法调用,而不是运行单独的线程。I think you need to
start
your thread - notrun
it. By calling run, you are just making a normal method call, not running a separate thread.您的代码中没有任何内容调用
ManualStopping
上的stopMe
方法。isInterrupted()
是一个不会更改线程状态的测试。正如@DaveHowes 指出的,你甚至不需要启动一个单独的线程。Nothing in your code calls the
stopMe
method onManualStopping
.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();
将其更改为t1.start()
。发生的情况是您打算生成的线程实际上并未作为单独的线程运行。相反,循环
while(!finished){ System.out.println("I'm Alive"); }
在主线程上运行,并且您的代码
num.crash(t1);
从未真正被调用。这导致了无限循环。t1.run();
Change it tot1.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.