1

是否可以用一个java命令执行两个单独的类?

我想为我的项目同时运行几个 java 程序(它应该同时启动)。

示例:我有两个 java 程序A.javaB.java.

编译

javac A.java B.java

java A B

但是,这不起作用。我还能怎么做?

4

4 回答 4

1

创建一个类,例如Parallel将其他类名作为命令行参数。然后为每个类启动一个新线程并调用它的主线程。

可能可以做得更整洁。

java Parallel A B

public class Parallel {

    public static void main(String[] args) {
        for (String arg : args) {
            try {
                Class<?> klazz = Class.forName(arg);
                final Method mainMethod = klazz.getDeclaredMethod("main",
                    String[].class);
                if (mainMethod.getReturnType() != void.class) {
                    throw new NoSuchMethodException("main not returning void");
                }
                int modifiers = mainMethod.getModifiers();
                if (!Modifier.isStatic(modifiers)
                    || !Modifier.isPublic(modifiers)) {
                    throw new NoSuchMethodException("main not public static");
                }
                Thread thread = new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            mainMethod.invoke(null, (Object)new String[0]);
                        } catch (IllegalAccessException
                            | IllegalArgumentException
                            | InvocationTargetException ex) {
                            Logger.getLogger(Parallel.class.getName())
                                .log(Level.SEVERE, null, ex);
                        }
                    }
                });
                thread.start();
            } catch (ClassNotFoundException
                | NoSuchMethodException
                | SecurityException ex) {
                Logger.getLogger(Parallel.class.getName())
                    .log(Level.SEVERE, null, ex);
            }                        
        }
    }
}
于 2013-05-13T08:15:43.673 回答
1

不,该java命令根本不能那样工作。

而是有一个C.java同时调用A&B类。

于 2013-05-13T07:46:09.720 回答
0

No matter how hard u try to start them simultaneously, the output will not be consistent. This won't work even if you try to load them through the third class.

What you can do is you need to handle this logic in your code. Possible options are -

  1. Run the objects in separate threads and make one join other.(this should be the ideal scenario. Both ways dependency is not good)
  2. Add logic in both programs to execute critical code at a same given time.(e.g. make both run at 16:00 EST). (Still i will say #1 option is better)
于 2013-05-13T08:00:53.017 回答
0

不,CPU 总是会像第一个命令一样启动一个命令,你可以做的是让两个线程等待一些通知它们启动,但即使那样我也会在内部猜测它们中的一个会先于另一个启动。

于 2013-05-13T07:53:36.273 回答