一个人如何停止一个线程没有stop()方法? [英] How does one stop a thread without a stop() method?
问题描述
我对Java线程问题。这里是我的情况:
I have question about the Java threads. Here is my scenario:
我有一个线程调用,可以采取当的方法。线程保持本身的方法,直到我得到的结果。如果我发送另一个请求,以同样的方式,方法,现在有两个线程运行(设置在第一未返回的结果尚未)。但我想给优先的最后一个线程,并且不希望得到从previously启动线程的结果。所以,当我没有停止方法,我怎么能摆脱早期线程?
I have a thread calling a method that could take while. The thread keeps itself on that method until I get the result. If I send another request to that method in the same way, now there are two threads running (provided the first did not return the result yet). But I want to give the priority to the last thread and don't want to get the results from the previously started threads. So how could I get rid of earlier threads when I do not have a stop method?
推荐答案
的标准设计模式是在可设定为停止它的线程使用本地变量
The standard design pattern is to use a local variable in the thread that can be set to stop it:
public class MyThread extends Thread {
private volatile boolean running = true;
public void stop() {
running = false;
}
public void run() {
while (running) {
// do your things
}
}
}
这种方式可以greacefully终止线程,也就是未抛出 InterruptedException的
。
这篇关于一个人如何停止一个线程没有stop()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!