Forking a process in Java

我的未来我决定 提交于 2019-12-01 21:07:02

You seem to be looking for the Java equivalent of the fork system call from Unix.

That does not exist in Java, and it's unclear whether it would even be possible, as processes in Unix don't have a direct equivalent in the JVM (threads are less independent than processes).

There is however a fork framework planned for Java 7:

http://www.ibm.com/developerworks/java/library/j-jtp11137.html

It's not the same as Unix'es fork/join, but it shares some ideas and might be useful.

Of course you can do concurrent programming in Java, it's just not done via fork(), but using Threads.

I'm not sure exactly what you're trying to do here. It sounds to me like you have a solution in mind to a problem that would best be solved in another way. Would something like this accomplish your end goal?

public class MyApp implements Runnable
  {
  public MyApp(int foo, String bar)
    {
    // Set stuff up...
    }

  @Override
  public void run()
    {
    // Do stuff...
    }

  public static void main(String[] argv)
    {
    // Parse command line args...

    Thread thread0 = new Thread(new MyApp(foo, bar));
    Thread thread1 = new Thread(new MyApp(foo, bar));

    thread0.start();
    thread1.start();
    }
  }

Though I would probably put main() in another object in a real app, since life-cycle management is a separate concern.

alamar

Well, using ProcessBuilder you can spawn another program.

See Java equivalent of fork in Java task of Ant?

Please read up on threads here and here.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!