立即停止线程 [英] Stopping thread Immediately
问题描述
我想立即停止正在运行的线程。这是我的代码:
I want to stop a running thread immediately. Here is my code:
A类:
public class A() {
public void methodA() {
For (int n=0;n<100;n++) {
//Do something recursive
}
//Another for-loop here
//A resursive method here
//Another for-loop here
finishingMethod();
}
}
B类:
public class B() {
public void runEverything() {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
A a = new A();
a.methodA();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
我的问题是我需要能够在B类中停止线程甚至在线程完成之前。我已经尝试过interrupt()方法,但这并没有阻止我的线程。我也听说使用共享变量作为一个信号来阻止我的线程,但我认为在我的进程中使用long recursive和for-loop,共享变量将无法生效。
My problem is that i need to be able to stop the thread in Class B even before the thread is finished. I've tried interrupt() method, but that doesn't stop my thread. I've also heard about using shared variable as a signal to stop my thread, but I think with long recursive and for-loop in my process, shared-variable will not be effective.
有什么想法吗?
提前致谢。
Any idea ? Thanks in advance.
推荐答案
Thread.interrupt
将不要停止你的线程(除非它处于睡眠状态,在这种情况下将抛出 InterruptedException
)。中断基本上向线程发送一条消息,指示它已被中断,但它不会导致线程立即停止。
Thread.interrupt
will not stop your thread (unless it is in the sleep, in which case the InterruptedException
will be thrown). Interrupting basically sends a message to the thread indicating it has been interrupted but it doesn't cause a thread to stop immediately.
当你有很长的循环操作时,使用一个标志检查线程是否已被取消是一种标准方法。您可以修改 methodA
以添加该标志,例如:
When you have long looping operations, using a flag to check if the thread has been cancelled is a standard approach. Your methodA
can be modified to add that flag, so something like:
// this is a new instance variable in `A`
private volatile boolean cancelled = false;
// this is part of your methodA
for (int n=0;n<100;n++) {
if ( cancelled ) {
return; // or handle this however you want
}
}
// each of your other loops should work the same way
然后可以添加一个取消方法来设置该标志
Then a cancel method can be added to set that flag
public void cancel() {
cancelled = true;
}
然后如果有人打电话给 runEverything
在 B
, B
然后只需拨打取消
在 A
上(您必须提取 A
变量,以便 B $ c $即使在调用
runEverything
之后,c>也会引用它。
Then if someone calls runEverything
on B
, B
can then just call cancel
on A
(you will have to extract the A
variable so B
has a reference to it even after runEverything
is called.
这篇关于立即停止线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!