开发者

How to stop the Swing EDT

The typical Swing application starts the EDT at the beginning and when the last window is closed the Application stops basically with a System.exit either implicit or explicit.

But my little application is actually a plugin for a framework which know开发者_如何转开发s nothing about Swing. My plugin will when called display a dialog, in order to get some input from the user and exit afterwards but the framework will/must keep running. So I can't call System.exit.

But if I don't do that the EDT will continue to run and once the framework is finished the EDT will still run and run and run ...

So I'd like to kill the EDT without killing the application. How do I do that?


The following document from Oracle/Sun shed some light on the issue: AWT Threading Issues

[...]

Prior to 1.4, the helper threads were never terminated.

Starting with 1.4, the behavior has changed as a result of the fix for 4030718. With the current implementation, AWT terminates all its helper threads allowing the application to exit cleanly when the following three conditions are true:

  • There are no displayable AWT or Swing components.
  • There are no native events in the native event queue.
  • There are no AWT events in java EventQueues.

Therefore, a stand-alone AWT application that wishes to exit cleanly without calling System.exit must:

  • Make sure that all AWT or Swing components are made undisplayable when the application finishes. This can be done by calling Window.dispose on all top-level Windows. See Frame.getFrames. ...
  • Make sure that no method of AWT event listeners registered by the application with any AWT or Swing component can run into an infinite loop or hang indefinitely. For example, an AWT listener method triggered by some AWT event can post a new AWT event of the same type to the EventQueue. The argument is that methods of AWT event listeners are typically executed on helper threads.

[...]


There may be some hidden windows (for example, dialogs displayed using JOptionPane.showMessageDialog(…) which are already closed) preventing Swing from exiting. You can check this using

Stream.of(Window.getWindows()).forEach(System.out::println);

If you don’t need them anymore, you can get rid of them easily:

Stream.of(Window.getWindows()).forEach(Window::dispose);

The Event Dispatch Thread should then stop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜