Suppose I run two java programs simultaneously on the same machine. Will the programs run in a single instance of JVM or will they run in two different instan开发者_如何转开发ces of JVM?
If you start each one with the java
command (from the command line) they will run as totally separate JVMs.
"Programs" may be started as separate Threads running inside the one JVM.
java
can just open start one application at a time, but you could write a simple launcher that takes class names as arguments and executes them in separate threads. A quick outline:
public class Launcher {
public static void main(String[] args) throws Exception {
for (int i = 0; i<args.length; i++) {
final Class clazz = Class.forName(args[i]);
new Thread(new Runnable() {
@Override
public void run() {
try{
Method main = clazz.getMethod("main", String[].class);
main.invoke(null, new Object[]{});
} catch(Exception e) {
// improper exception handling - just to keep it simple
}
}
}).start();
}
}
}
Calling it like
java -cp <classpath for all applications!> Launcher com.example.App1 com.example.App2
should execute the application App1 and App2 inside the same VM and in parallel.
Assuming that you meant processes by the word programs, then yes, starting two processes, will create two different JVMs.
A JVM process is started using the java application launcher; this ought to provided with an entry-point to your program, which is the main method. You may link to other classes from this entry-point, and from other classes as well. This would continue to occur within the same JVM process, unless you launch another process (to run another program).
It depends on the platform and the JVM implementation, but typically they would run in separate VMs.
Will the programs run in a single instance of JVM or will they run in two different instances of JVM?
That is up to you. The simplest approach is to use separate JVMs.
What you could do is use two separate threads. For exampe
new Thread() {
public void run() {
System.out.println("this is running separately from the main thread!");
}
}.start();
If you want two separate programs to interact you would need to use sockets
精彩评论