Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I start multiple main programs in a Java executable .jar?

Tags:

java

main

launch

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!

like image 264
Brian Avatar asked May 11 '11 00:05

Brian


People also ask

Can a jar have multiple main classes?

Jar files can contain only one Main-Class attribute in the manifest, which means a jar can contain only one mainClassName.

How to set main class in Java project?

Right-click the user name package and select New -> Java Main Class... Name your class Menu . Run the project. You will be prompted to select the main class.

How do I run a Java executable jar in another Java program?

To run an application in a nonexecutable JAR file, we have to use -cp option instead of -jar. We'll use the -cp option (short for classpath) to specify the JAR file that contains the class file we want to execute: java -cp jar-file-name main-class-name [args …]


2 Answers

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.

like image 132
Synesso Avatar answered Oct 26 '22 16:10

Synesso


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

like image 23
fmucar Avatar answered Oct 26 '22 17:10

fmucar