How do I start multiple main programs in a Java ex

2019-02-02 08:47发布

I'm writing a program that contains multiple packages in it. Each package has its own main program that I want all to launch simultaneously when the .jar is executed by an interpreter. This seems like a fairly simple question, but when I looked around, it seems that people are using ants (which I've never used before) and other methods. Is there a simpler way in Eclipse to compile a .jar with multiple launch configurations, better yet, is there a way to hard code it in?

If the best way to launch this is through an ant. What kind of ant script would I write if I want to the launch... say the main programs in packets com.myapp.package1.main, com.myapp.package2.main, and com.myapp.package3.main. Thanks in advance!

标签: java main launch
3条回答
男人必须洒脱
2楼-- · 2019-02-02 09:16

You can create one main "main" class which executes the rest.

查看更多
乱世女痞
3楼-- · 2019-02-02 09:18

The jar manifest allows you to optionally specify no more than one main class. This is invoked when you execute java with the -jar flag.

java -jar myapp.jar

You may include multiple main classes in a single jar, but each (except the optional 1 above) must be invoked using the -classpath flag and with the fully qualified name of the main class specified.

java -classpath myapp.jar com.mypackage.app.Main01 && \
  java -classpath myapp.jar com.mypackage.app.Main02 && \
  java -classpath myapp.jar com.mypackage.app.Main03

The example above will spawn three separate java VMs, each in their own process. Obviously, this does not meet your requirement for an 'executable jar'.

Alternatively, you may wish to have one main method that starts separate threads, so that there is only one process, but concurrent execution.

Ant is not a suitable choice to help you solve this issue. I suspect you probably want a single main method that spawns multiple threads. Feel free to provide more information on your requirements.

查看更多
倾城 Initia
4楼-- · 2019-02-02 09:27

Probably I would stick to the MANIFEST solution, but there is another possibility for this to be done:

Process p = Runtime.getRuntime().exec("java -jar another.jar");

But here you should be careful with path and should properly end process, else your machine can reach the limit for file descriptors.

查看更多
登录 后发表回答