开发者

Process forking, child processes etc. [Java]

开发者 https://www.devze.com 2023-02-10 00:18 出处:网络
I need to implement vector clocks in a small programmin开发者_运维百科g exercise and I decided to use Java for it. My question is not related to the actual algorithm of manipulating the vector clocks

I need to implement vector clocks in a small programmin开发者_运维百科g 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, e.g.,:

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
    }
}


Have a look at this answer for C-like forks in Java.

0

精彩评论

暂无评论...
验证码 换一张
取 消