简体   繁体   中英

Communication between processes (main) Java

I need to communicating various processes as it follows:

First I invoke GeneralMain with args[0] = 1, so it will call A.main().

The two remaining processes will launch in a space of random time, but both processes need to start at the same time.

My code:

public class GeneralMain {

    public static void main(String[] args) {
        int num_proc = Integer.parseInt(args[0]);

        switch (num_proc) {
            case 1:
                A.main(...);
                break;

        case 2:
            B.main(...);
            break;

            case 3:
                C.main(...);
                break;

            default:
                break;
        }
    }
}

First the GeneralMain recieve args[0] = 1, and calls A.main(); .

So, I execute the GeneralMain for three times. In the first time A.main() is started and is the responsible of recieve messages, Then I execute GeneralMain that start B.main() process and send the first message to A. To end, I execute GeneralMain that start C.main() process and send the second message to A, but I need that B.main() and C.main() starts at the same time and send his message at the same time

Thanks.

You might look at using threads and runnable's.

From main you could start A then start 2 threads using a random time at which they would both start. One thread calls B and the other calls C.

You can use a cyclic barrier to make sure B and C start executing their logic at the same time.

CyclicBarrier cyclicBarrier = new CyclicBarrier(2); //global scope

B { //thread B's main
    cyclicBarrier.await(); //wait for other thread
}
C { //thread C's main
    cyclicBarrier.await(); //wait for other thread
}

Basically both B and C will register themselves at the barrier and as soon as the registered parties number reaches 2 the barrier will trip and B and C will start executing their logic at more or less the same time (not sure how exact the synchronization is)

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