输入中文以后 Java 并不退出

以前似乎也发现过,不过都没有注意,今天是在一个很简单的情况下出来的,然后稍微试验了一下就发现,在输入中文以后,程序就不能正常退出了,当然,没有直接使用 System.exit() 方法来暴力退出。这里说一下 Java 的退出方法,一般有两种:

  • 调用 System.exit():这就直接让 JVM 退出,相对来讲比较暴力,它不管你还有其他什么线程在运行,直接退出。
  • 所有非守护(daemon)线程都结束以后,JVM 自己正确退出。这种方法相对来说比较“优雅”,如果一个要退出必须正确地结束所有相关线程,这是一个很好的习惯。

在我的程序中没有使用 System.exit(),所以现在碰到上面问题以后并不能完全退出。简单的测试程序如下:

  1. import java.awt.event.ActionEvent;
  2. import java.awt.BorderLayout;
  3. import javax.swing.JFrame;
  4. import javax.swing.JButton;
  5. import javax.swing.JTextField;
  6. import javax.swing.AbstractAction;
  7.  
  8. public class Test extends JFrame {
  9.     public Test() {
  10.         super("Test");
  11.  
  12.         JTextField tf = new JTextField();
  13.         getContentPane().add(tf);
  14.  
  15.         JButton button = new JButton(new AbstractAction("Close") {
  16.                 public void actionPerformed(ActionEvent event) {
  17.                     Test.this.dispose();
  18.                 }
  19.             }
  20.             );
  21.         getContentPane().add(button, BorderLayout.SOUTH);
  22.  
  23.         pack();
  24.         setVisible(true);
  25.     }
  26.  
  27.     public static void main(String[] args) {
  28.         new Test();
  29.     }
  30. }

在 Windows XP 下,两个版本的 JDK 都重现了这个问题。Linux 暂时没试过。

  1. java version "1.6.0_01"
  2. Java(TM) SE Runtime Environment (build 1.6.0_01-b06)
  3. Java HotSpot(TM) Client VM (build 1.6.0_01-b06, mixed mode, sharing)
  4.  
  5. java version "1.5.0_08"
  6. Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_08-b03)
  7. Java HotSpot(TM) Client VM (build 1.5.0_08-b03, mixed mode, sharing)

当然绕过问题而解决的办法也不是没有,感觉不是很完美。不过这个问题应该是个 bug。

更新:Linux 似乎没有问题。

  1. java version "1.5.0_06"
  2. Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_06-b05)
  3. Java HotSpot(TM) Server VM (build 1.5.0_06-b05, mixed mode)

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote>
  • You can use BBCode tags in the text.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. The supported tag styles are: <foo>, [foo].
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
  _  __  _   _   _____       _           ____    _____   _     
| |/ / | | | | |_ _| | | _ __ | _ \ | ___| | |__
| ' / | | | | | | _ | | | '_ \ | | | | | |_ | '_ \
| . \ | |_| | | | | |_| | | | | | | |_| | | _| | | | |
|_|\_\ \___/ |_| \___/ |_| |_| |____/ |_| |_| |_|
Enter the code depicted in ASCII art style.