简体   繁体   中英

Process forking, child processes etc. [Java]

I need to implement vector clocks in a small programming exercise and I decided to use Java for it. My question is not related to the actual algorithm of manipulating the vector clocks of processes, but how to initialize other Java applications or child processes relatively easy from another Java program?

My initial plan is the following: I have a "main program", which decides how many clients/children to start and then these children/clients should communicate with each other and update their corresponding vector clocks accordingly. The number of clients to be started depends on the number of lines in a certain input file given to the "main program". What is the most elegant way to start these client processes? They should each take two files and an integer as parameters. The files tell what to do (send or advance clock) and the integer tells from which line in a configuration file the client should pick its port number to be used.

In java, the concept of creating concurrent tasks is based on threads rather than processes . To start a new process , you must typically invoke java multiple times or use the ProcessBuilder interface. Concurrency in java is designed for threads, so that's what I'll recommend you to try, eg,:

public static void main(String[] args) {
    int numberOfThreads  = ...
    for(int i = 0; i < numberOfThreads; i++) {
        File f1 = ...
        File f2 = .... 
        int j = ... 

        new Thread(new VectorClock(f1, f2, j)).start();
    }
}

public class VectorClock implements Runnable {
    public VectorClock(File file1, File file2, int i) {
       // ...
    }

    @Override
    public void run() {
        // this gets executed when invoked by a threads .start() routine
    }
}

看看Java中类似C的fork的答案

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM