[英]How do I stop a custom Thead in SWT application?
How do I stop a custom Thread when I exit my SWT application? 退出SWT应用程序时如何停止自定义线程?
MyThread
runs in an infinite loop, until a certain condition becomes true: MyThread
在无限循环中运行,直到满足特定条件为止:
class MyThread extends Thread {
@Override
public void run() {
do {
// Do stuff...
}
while (!this.isInterrupted() && otherCondition);
}
In my SWT application I do start the thread and try to stop in in the SWT composite's dispose()
method. 在我的SWT应用程序中,我确实启动了线程,并尝试在SWT组合的dispose()
方法中停止。 However, this method is never called. 但是,永远不会调用此方法。
class MyComposite extends Composite {
private MyThread myThread = null;
@Override
public void dispose() {
super.dispose();
if (null != this.myThread) {
this.myThread.interrupt();
}
}
public void somewhere() {
this.myThread = new MyThread();
this.myThread.start();
}
}
Now, it can happen that I have closed my SWT application window already, but the thread keeps running (it still creates debug output). 现在,可能已经关闭了我的SWT应用程序窗口,但是线程继续运行(它仍然创建调试输出)。 Isn't the dispose()
method called automatically? dispose()
方法不是自动调用的吗? What is the best way to make the thread stop, if the user closes the application window? 如果用户关闭应用程序窗口,使线程停止的最佳方法是什么?
All controls are disposed when their parent window is closed, but not by calling their dispose
method (an internal method called release
is called). 所有控件均在其父窗口关闭时被处置,但不通过调用其dispose
方法(称为内部方法release
)来dispose
。 So as mentioned in another answer you need to use a DisposeListener
to be informed about the dispose. 因此,正如另一个答案中所提到的,您需要使用DisposeListener
来通知有关该处置的信息。
Alternatively your thread can call setDaemon(true)
- the JVM does not wait for daemon threads to stop when closing an application. 或者,您的线程可以调用setDaemon(true)
-关闭应用程序时,JVM不等待守护程序线程停止。
You have to dispose()
your widgets by yourself. 您必须自己dispose()
小部件。 I do not know how you get rid of your widgets since the snippet does not contain any code for that. 我不知道您如何摆脱小部件,因为该代码段不包含任何代码。
Every class that extends Widget
allows registering a DisposeListener
(using addDisposeListener()
method). 每个扩展Widget
类都允许注册一个DisposeListener
(使用addDisposeListener()
方法)。 As soon as a widget is disposed you'll be notified. 放置小部件后,您会收到通知。
Btw. 顺便说一句。 you've got maybe a typo, your if
checks if this.checker
is not null and your thread field is named myThread
您可能输入错误, if
检查this.checker
是否不为null且您的线程字段名为myThread
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.