多线程-杀死线程及其所有子进程 [英] Multithreading - Killing a Thread and all its child processes
问题描述
我正在开发一个分析应用程序.在Java中是这样.在顶部,我有一个带有开始"和停止"按钮的GUI.单击开始"后,我在其中创建了一个线程,其RUN方法在内部调用了一个API方法,该方法在内部创建了一个线程.
单击开始" ----->生成了一个线程---->在此线程的RUN方法中,我使用了一个API cal,它在内部创建了一个线程...
现在,我想要的是当我单击STOP GUI按钮时,由API调用创建的内部线程也应该消失..
我该如何实现?
谢谢
您将必须对线程类实现一些逻辑.首先,它们需要一些杀死开关"-您不能(不应!)从外面阻止它们.我们通常在线程实例上定义并设置一个标志,以便它知道何时必须终止.
然后,我们没有线程层次结构".线程实例将需要其自己的子线程列表,并且,如果它(父)接收到停止信号,则必须将相同的信号发送给它的子线程.
public abstract class MyThread extends Thread {
private List<MyThread> children = new ArrayList<MyThread>();
private boolean stopNow = false; // <- this is the stop flag
public void stopNow() {
for (MyThread thread:children) {
thread.stopNow();
}
stopNow = true;
}
}
(这实际上不会使线程停止,我们必须在run
方法中监视" stopNow
标志).
I am working on an analytics app. in Java.At the top i have a GUI which has START and STOP Buttons.On Clicking Start i create a Thread inside whose RUN method i call an API method which internally creates a Thread.i.e.
On Clicking "START"----->a Thread is Spawned---->in this thread's RUN method i use an API cal which creates a thread Internally...
Now,what i want is that when i click the STOP GUI button,the internal thread created by the API call should also die..
How can i achieve that??
Thanks
You'll have to implement some logic to the thread classes. First, they need some "kill switches" - you can't (shouldn't!!) stop them from outside. We usually define and set a flag on the thread instance so that it knows, when it has to terminate.
Then, we don't have a thread "hierarchy". A thread instances will need to its own list of child threads and, if it (the parent) receives the stop signal, it will have to send the same signal to its children.
public abstract class MyThread extends Thread {
private List<MyThread> children = new ArrayList<MyThread>();
private boolean stopNow = false; // <- this is the stop flag
public void stopNow() {
for (MyThread thread:children) {
thread.stopNow();
}
stopNow = true;
}
}
(This will not make a thread stop actually, we'll have to "monitor" the stopNow
flag in the run
method).
这篇关于多线程-杀死线程及其所有子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!