Reputation: 7899
I am looking for some more knowledge about java main method public static void main(String[] args)
.When JVM call main method it creates Main thread and the whole program is get executed in this Main thread until some user thread explicitly get started in its own stack.
My question is that is it possible to start main
thread from some other main
method?
Its better if someone can give me some reference about main thread.
Upvotes: 3
Views: 2271
Reputation: 7795
class FirstApp { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { SecondApp.main(args); } }).start();
Starts a new thread and calls the main method of another application. Works fine. But they run both in the same process.
However, if you want to do it as if it was executed from command line (in another (separate) process), you can also do something like this:
import java.io.File; import java.io.IOException; import java.lang.management.ManagementFactory; public class Main { public static void main(String[] args) throws IOException, InterruptedException { StringBuilder cmd = new StringBuilder(); cmd.append(System.getProperty("java.home") + File.separator + "bin" + File.separator + "java "); for (String jvmArg : ManagementFactory.getRuntimeMXBean().getInputArguments()) { cmd.append(jvmArg + " "); } cmd.append("-cp ").append(ManagementFactory.getRuntimeMXBean().getClassPath()).append(" "); cmd.append(Main2.class.getName()).append(" "); // Main2 is the main class of the second application for (String arg : args) { cmd.append(arg).append(" "); } Runtime.getRuntime().exec(cmd.toString()); // continue with your normal app code here } }
I took the second code mostly from How can I restart a Java application?
Upvotes: 0
Reputation: 19492
As far as my knowledgee, main thread is started by the JVM and the other threads started by the user are the sub-thread of the main thread in that thread group.
Upvotes: 0
Reputation: 40333
The main thread is just a concept, it's a name for the thread that starts your app, this thread is not special in any way (other than not being a daemon thread) so you can easily create new threads that are not daemons also and call another main method on them.
There isn't anything special about being the main thread, it's just the first thread to be started.
Upvotes: 8