Simultaneously run java programs run on same JVM?

后端 未结 6 2098
旧巷少年郎
旧巷少年郎 2020-12-08 01:33

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 instances of JVM?

相关标签:
6条回答
  • 2020-12-08 01:40

    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.

    0 讨论(0)
  • 2020-12-08 01:46

    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).

    0 讨论(0)
  • 2020-12-08 01:47

    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.

    0 讨论(0)
  • 2020-12-08 01:49

    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.

    0 讨论(0)
  • 2020-12-08 01:52

    It depends on the platform and the JVM implementation, but typically they would run in separate VMs.

    0 讨论(0)
  • 2020-12-08 01:56

    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

    0 讨论(0)
提交回复
热议问题