Java中如何终止这样的线程
可能的重复:
如何杀死java线程?
我的应用程序中有如下线程一。
我怎样才能终止它们?
new Thread(new Runnable() {
public void run() {
// do it…
}
}).start();
编辑:
解决方案:
Class Memory{
static Runnable last;
}
这会将我们的线程保存在 var 中。
new Thread(new Runnable() {
public void run() {
Memory.last = this;
// do it…
}
}).start();
现在在你想要停止的任何部分:
Memory.last.wait(); //will pause but next new thread will terminate it (garbage collector do this );
Possible Duplicate:
How to kill a java thread ?
I have threads in my app like the below one.
How can I terminate them?
new Thread(new Runnable() {
public void run() {
// do it…
}
}).start();
Edit:
Solution:
Class Memory{
static Runnable last;
}
This will save our Thread in a var.
new Thread(new Runnable() {
public void run() {
Memory.last = this;
// do it…
}
}).start();
now in any part you want stop:
Memory.last.wait(); //will pause but next new thread will terminate it (garbage collector do this );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 run() 方法中,您可以定期调用
interrupted()
来测试线程是否被中断,然后静默退出或抛出 InterruptedException。要停止线程,您可以调用它的interrupt()
方法。有关详细信息,请参阅中断中的 Java 教程。Inside your run() method, you can periodically call
interrupted()
to test whether the thread is interrupted, and then either exit silently or throw an InterruptedException. To stop the thread you can call it'sinterrupt()
method. See the Java tutorial in interrupts for more info.当 run 方法完成时,它们将停止运行。根据您在该方法中输入的内容,它们将立即停止或永远运行。
如果它们有循环,您必须将该线程条件更改为 false。
They'll stop running when it's run method is done. Depending on what you put in that method they'll stop immediately or would run forever.
If they have a loop you have to change that thread condition to false.