背景
我在准备使用 JVM 的命令时候观察程序的动态,但是发现 Main 函数启动就退出了,所以也没办法直接观察,于是想到了如何让 Main 函数启动一直不退出,这样就可以该干啥就干啥啦~
方案
1、System.in.read()
简单粗暴(推荐)
1
2
3
4
5
|
public static void main(String[] args) throws IOException { System.out.println( 1 ); System.in.read(); System.out.println( 2 ); } |
2、Object.wait()
这个还需要 synchronized 配合使用,繁琐
1
2
3
4
5
6
7
8
|
public static void main(String[] args) throws InterruptedException { System.out.println( 1 ); Object o = new Object(); synchronized (o) { o.wait(); } System.out.println( 2 ); } |
3、Thread.sleep(9999999)
让线程睡觉,睡久点,这个也还行吧,比第二种简单点,就是有时间限制,当然有些场景还真需要这种来控制动态
1
2
3
4
5
|
public static void main(String[] args) throws InterruptedException { System.out.println( 1 ); Thread.sleep( 9999999 ); System.out.println( 2 ); } |
到此这篇关于Java Main 函数启动不退出的方法的文章就介绍到这了,更多相关Java Main 函数启动不退出内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/Dream_Weave/article/details/124964787