开发者

How many ways a java Program can end?

I know use System.exit(0) can end a java program, for i开发者_StackOverflow中文版nstance, if I have a JFrame window, it will close and end the program, but I wonder how many other ways, can it be closed and the program be ended ? Including when an error occurs, will the program be shut down and the JFrame be closed ?


To add to other answers:

  • If the process that is hosting the VM is forcefully terminated, your program will spontaneously disappear
  • The same happens if the plug gets pulled on the machine hosting the VM :)


A Java program ends when the last Thread without daemon flag ends, or when you call a method that shuts down the virtual machine (System.exit(), Runtime.exit(), Runtime.halt() and possibly a few more).

Anything else is up to libraries that call System.exit() (such as a JFrame with EXIT_ON_CLOSE).


Here's all I can think of off the top of my head:

  1. main() returns (either a value or a void() main finishes executing its last statement)

  2. program throws an exception uncaught

  3. System.exit(int)

  4. It can crash?

In your case of a JFrame closing, I believe there would be an onClose() handler which either calls System.exit(0) or causes the main method to return.


One other way the Java program ends is when the last statement in the java code is executed. Also when java.lang.OutOfMemory error occurs, the program terminates abnormally. This occurs when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.


I've answered your question in the context of Swing GUIs given your mentioning of JFrame.

  • With a Swing GUI the Event Dispatch thread will log any exceptions that occur but will not terminate the application in this situation.
  • Similarly, if another thread throws an exception and terminates the Event Dispatch thread will ensure that the application is kept alive (as it is not a daemon thread).
  • One final point: If you wish your application to be terminated when a JFrame is closed, you need to call: setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

Otherwise the frame will simply be hidden when you close it, but the application will continue to run.


You can end a running Java program externally. By killing the java.exe process from task manager (in case of windows)


You can use Application.exit() as well.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜