我们可以在没有main()方法的情况下执行程序吗? [英] Can we execute a program without main() method?

查看:113
本文介绍了我们可以在没有main()方法的情况下执行程序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以在没有main方法的情况下执行程序吗?在java中如何告诉我任何示例。你做过那样的例子。

Can we execute a program without main method and how in java tell me any example. have you done that kind of example.

推荐答案

是的,有可能:

public class MyClass {
    static {
        Runnable r = new Runnable() {
            public void run() {
                // whatever you like
            }
        };
        Thread t = new Thread(r)
        t.start();
        t.join();
    }
}

现在运行java将此类传递给命令。 Java在尝试运行其main(不存在)之前加载该类,但在加载类时,它会触发静态块,该块将停止直到线程完成。

Now you run java passing this class to the command. Java loads the class before attempting to run its main (which doesn't exist), but in loading the class, it fires the static block, which halts until the thread finishes.

如果线程在没有退出的情况下完成,java会抱怨没有主要方法,但到那时线程可以在任何时间内运行任何东西。

If the thread finishes without exiting, java will complain there's no main method, but by that time the thread could have run anything for any duration.

你将拥有在那里捕捉一些例外,但它会起作用。

You'll have to catch some exceptions in there, but it will work.

这篇关于我们可以在没有main()方法的情况下执行程序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆