JrL*_*JrL 6 java multithreading
我想立即停止正在运行的线程.这是我的代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我需要能够在线程完成之前在B类中停止线程.我已经尝试过interrupt()方法,但这并没有阻止我的线程.我也听说过使用共享变量作为一个信号来阻止我的线程,但我认为在我的进程中使用long recursive和for循环,共享变量将无效.
任何的想法 ?提前致谢.
Jef*_*rey 13
Thread.interrupt不会停止你的线程(除非它处于睡眠状态,在这种情况下InterruptedException将被抛出).中断基本上向线程发送一条消息,指示它已被中断,但它不会导致线程立即停止.
当您进行长循环操作时,使用标志来检查线程是否已被取消是一种标准方法.您methodA可以修改为添加该标志,如下所示:
// 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
Run Code Online (Sandbox Code Playgroud)
然后可以添加取消方法来设置该标志
public void cancel() {
cancelled = true;
}
Run Code Online (Sandbox Code Playgroud)
那么,如果有人要求runEverything上B,B然后只需调用cancel上A(你将不得不提取A变量,B 必须对它的引用,即使之后runEverything被调用.