dcsimg
Is there some way to implement multi-tasking in Java (like "fork()" on UNIX)?
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Motor_Qian
Posted On:   Monday, April 9, 2001 12:12 AM

I've been wondering for a while, for I've never seen anything about Java multi-process.
Is there some way to implement Java multi-process like "fork()" on UNIX. Because JVM is a platform independent machine, so we could not control processes, that's operating-system featrues. I need process control over JVM.

Thank you very much.

Re: Is there some way to implement multi-tasking in Java (like "fork()" on UNIX)?

Posted By:   Finlay_McWalter  
Posted On:   Tuesday, June 12, 2001 03:57 PM

There isn't anything very portable, but (if you're willing to provide an implementation for each of your target platforms) you can either:

  • Have the host OS execute a new JVM (typically by calling Runtime.exec()) and pass it the name of the classfile you want to "fork" to.
  • Use JNI (from C code) to create a new JVM

Neither of these is as good as fork, as the new subprogram doesn't inherit any of the state of its parent.


If you can possibly help it, try to avoid the need for this functionality in the first place, by using a Java application framework like JES (Java Embedded Server). This limits a few of
the things you might like to do (mostly security and classloader stuff) but allows multiple programs to coexist in the same JVM. This has the additional benefit that it's much more efficient than a true fork - you still have only one JVM instance and only one OS process, which is much lighter weight than creating multiple processes each running a JVM.

Re: Is there some way to implement multi-tasking in Java (like "fork()" on UNIX)?

Posted By:   Luigi_Viggiano  
Posted On:   Sunday, May 6, 2001 05:30 PM

Yes of course! Java has his multithread mechanism enbedded as language core feature.
Try this short code:

public class SimpleThread extends Thread {

int number;

public void run() {
for (int i = 1; i < 5; i++) {
System.out.println("Hello from thread number " + number);
try {
sleep(number* 500);
} catch (InterruptedException ie) {}
}
}

public SimpleThread(int threadNumber) {
number = threadNumber;
start();
}

public static void main(String[] args) throws Exception {
new SimpleThread(1);
new SimpleThread(2);
new SimpleThread(3);
}
}
About | Sitemap | Contact